- JavaScript Alert [Examples And Usage]
- Examples using alert
- 1. Alert message on click
- 2. Alert box before closing the window
- 3. Alert box on page load
- 4. Alert message using a variable
- 5. Alert a message requiring confirmation
- 6. Alert a message showing input field
- 7. Alerts with custom styles
- Related articles
- Свойства и методы формы
- Навигация: формы и элементы
- Обратная ссылка: element.form
- Элементы формы
- input и textarea
- select и option
- new Option
- Ссылки
- Итого
JavaScript Alert [Examples And Usage]
Note that, when executed, the alert function will get the focus and prevent the user from interacting with the reset of the website until the modal gets dismisssed.
Examples using alert
1. Alert message on click
A very common use case for the alert fuction is to use it when filling a form and then trying to submit it by clicking a button.
Let’s say we want to make sure the user is over 18 years old when filling the following form:
form name="myForm" action="">
label for="age">Agelabel>
input type="number" name="age" id="age" />
button type="submit">Submitbutton>
form>
All we have to do is attach an event listener to the button, checking for the value of the input field and then displaying the modal with the alert function of JavaScript:
var checkAge = (e) =>
if(document.querySelector('#age').value 18)
// Preventing the submit of the form
e.preventDefault();
// Displaying the modal window
alert("You have to be older 18!");
>
>;
// Listening to the click event on the button
document.querySelector('button').addEventListener('click', checkAge);
2. Alert box before closing the window
It’s also a common practise in websites that require saving changes to display an alert message when the user tries to close the browser’s window or tab.
To do this, we have to first detect when the user is about to close the window. We can achieve this in two different ways, but it’s usually recommended to use event listeners when possible.
// Using event listeners
window.addEventListener("beforeunload", showDialog);
// Overwriting the window default property function
window.onbeforeunload = showDialog;
Now all we have to do is show them a dialog. But in this case, we won’t be using the alert function for this scenario.
Unfortunately we can not customise the message that gets displayed on the dialog anymore. We still have to return a text for old browsers compatibility, but the message will most likely not get displayed on modern browsers. They’ll show a default message telling the user that changes won’t get saved.
So, here’s how we tell the browser we want to show a message, but returning a string on the event function:
var showDialog = (e) =>
return 'Dialog text here.';
>;
window.addEventListener("beforeunload", showDialog);
3. Alert box on page load
In some very specific cases, websites might want to show an alert message on page load. To do this all we need to do is fire the alert message on the section of our HTML. This way, the alert will be shown before loading any elements on the page.
head>
script>
alert("Displayed before page loads");
/script>
/head>
body>
Your page content.
/body>
4. Alert message using a variable
Using a variable to display different messages based on its content can also be done quite easily. Simply pass the variable to the alert method instead of a string text.
var myVariable = 'I love alert boxes!!';
alert(myVariable);
5. Alert a message requiring confirmation
Perhaps you want to show an alert that requires the visitors confirmation and that allows them too also cancel or ignore it by displaying a «Cancel» and an «OK» buttons. For these cases we will use the confirm function, which can be seen as a variant of the alert function.
The confirm function will just add a «Cancel» button on top of the «OK» one added by the alert method.
confirm('Do you want to continue?');
We can catch the visitor’s decision by checking the result of the method. It will be true if the visitor clicks on «OK» and false otherwise.
if(confirm("Do you want to continue?"))
// continue heree
>
6. Alert a message showing input field
In some occassions we might want to capture the user input directly on the alert message. In this cases we will also move away from the alert function and use the alternative function prompt . This function creates the same dialog box but adds a text field to it and the «Cancel» button too.
It admits twoo parameters. The first one is the text to show on the dialog (for the input) and the second one is the default value for the input (if any).
// Showing a dialog box with a text input containing "Steve"
prompt("Enter your name, please:", "Steve");
// Showing a dialog box with ab empty text input.
prompt("Enter your name, please:");
7. Alerts with custom styles
In order to use your own custom alert modals we’ll have to make use of JavaScript and CSS. The easiest, fastest and probably most reliable way to do it is by using external plugins instead of doing it by yourself.
One of the most used ones is SweetAlert2 , or even its predecesor SweetAlert.
Here’s an example of how a confirm alert dialog looks like when using this component:
var showConfirm = (e) =>
e.preventDefault();
Swal.fire(
title: 'Error!',
text: 'Do you want to continue',
confirmButtonText: 'Yeap!'
>);
>;
document.querySelector('button').addEventListener('click', showConfirm);
As you can see there aren’t huge changes in our code and the usage is quite straight away.
You can check more alert examples using this component on their website.
There are other dialog boxes plugins out there, so feel free to choose the one that fits your needs.
Related articles
Свойства и методы формы
Формы и элементы управления, такие как , имеют множество специальных свойств и событий.
Работать с формами станет намного удобнее, когда мы их изучим.
Навигация: формы и элементы
Формы в документе входят в специальную коллекцию document.forms .
Это так называемая «именованная» коллекция: мы можем использовать для получения формы как её имя, так и порядковый номер в документе.
document.forms.my - форма с именем "my" (name="my") document.forms[0] - первая форма в документе
Когда мы уже получили форму, любой элемент доступен в именованной коллекции form.elements .
Может быть несколько элементов с одним и тем же именем, это часто бывает с кнопками-переключателями radio .
В этом случае form.elements[name] является коллекцией, например:
Эти навигационные свойства не зависят от структуры тегов внутри формы. Все элементы управления формы, как бы глубоко они не находились в форме, доступны в коллекции form.elements .
Форма может содержать один или несколько элементов внутри себя. Они также поддерживают свойство elements , в котором находятся элементы управления внутри них.
Есть более короткая запись: мы можем получить доступ к элементу через form[index/name] .
Другими словами, вместо form.elements.login мы можем написать form.login .
Это также работает, но есть небольшая проблема: если мы получаем элемент, а затем меняем его свойство name , то он всё ещё будет доступен под старым именем (также, как и под новым).
В этом легче разобраться на примере:
Обычно это не вызывает проблем, так как мы редко меняем имена у элементов формы.
Обратная ссылка: element.form
Для любого элемента форма доступна через element.form . Так что форма ссылается на все элементы, а эти элементы ссылаются на форму.
Элементы формы
Рассмотрим элементы управления, используемые в формах.
input и textarea
К их значению можно получить доступ через свойство input.value (строка) или input.checked (булево значение) для чекбоксов.
input.value = "Новое значение"; textarea.value = "Новый текст"; input.checked = true; // для чекбоксов и переключателей
Обратим внимание: хоть элемент и хранит своё значение как вложенный HTML, нам не следует использовать textarea.innerHTML для доступа к нему.
Там хранится только тот HTML, который был изначально на странице, а не текущее значение.
select и option
Элемент имеет 3 важных свойства:
- select.options – коллекция из подэлементов ,
- select.value – значение выбранного в данный момент ,
- select.selectedIndex – номер выбранного .
Они дают три разных способа установить значение в :
- Найти соответствующий элемент и установить в option.selected значение true .
- Установить в select.value значение нужного .
- Установить в select.selectedIndex номер нужного .
Первый способ наиболее понятный, но (2) и (3) являются более удобными при работе.
Вот эти способы на примере:
В отличие от большинства других элементов управления, позволяет нам выбрать несколько вариантов одновременно, если у него стоит атрибут multiple . Эту возможность используют редко, но в этом случае для работы со значениями необходимо использовать первый способ, то есть ставить или удалять свойство selected у подэлементов .
Их коллекцию можно получить как select.options , например:
new Option
Элемент редко используется сам по себе, но и здесь есть кое-что интересное.
В спецификации есть красивый короткий синтаксис для создания элемента :
option = new Option(text, value, defaultSelected, selected);
- text – текст внутри ,
- value – значение,
- defaultSelected – если true , то ставится HTML-атрибут selected ,
- selected – если true , то элемент будет выбранным.
Тут может быть небольшая путаница с defaultSelected и selected . Всё просто: defaultSelected задаёт HTML-атрибут, его можно получить как option.getAttribute(‘selected’) , а selected – выбрано значение или нет, именно его важно поставить правильно. Впрочем, обычно ставят оба этих значения в true или не ставят вовсе (т.е. false ).
let option = new Option("Текст", "value"); // создаст
Тот же элемент, но выбранный:
let option = new Option("Текст", "value", true, true);
option.selected Выбрана ли опция. option.index Номер опции среди других в списке . option.value Значение опции. option.text Содержимое опции (то, что видит посетитель).
Ссылки
Итого
Свойства для навигации по формам:
document.forms Форма доступна через document.forms[name/index] . form.elements Элементы формы доступны через form.elements[name/index] , или можно просто использовать form[name/index] . Свойство elements также работает для . element.form Элементы хранят ссылку на свою форму в свойстве form .
Значения элементов формы доступны через input.value , textarea.value , select.value и т.д. либо input.checked для чекбоксов и переключателей.
Для элемента мы также можем получить индекс выбранного пункта через select.selectedIndex , либо используя коллекцию пунктов select.options .
Это были основы для начала работы с формами. Далее в учебнике мы встретим ещё много примеров.
В следующей главе мы рассмотрим такие события, как focus и blur , которые могут происходить на любом элементе, но чаще всего обрабатываются в формах.