Show alert message in javascript

How TO — Alerts

Alert messages can be used to notify the user about something special: danger, success, information or warning.

Create An Alert Message

Step 1) Add HTML:

Example

If you want the ability to close the alert message, add a element with an onclick attribute that says «when you click on me, hide my parent element» — which is the container (class=»alert»).

Tip: Use the HTML entity » × » to create the letter «x».

Step 2) Add CSS:

Style the alert box and the close button:

Example

/* The alert message box */
.alert padding: 20px;
background-color: #f44336; /* Red */
color: white;
margin-bottom: 15px;
>

/* The close button */
.closebtn margin-left: 15px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
line-height: 20px;
cursor: pointer;
transition: 0.3s;
>

/* When moving the mouse over the close button */
.closebtn:hover color: black;
>

Many Alerts

If you have many alert messages on a page, you can add the following script to close different alerts without using the onclick attribute on each element.

And, if you want the alerts to slowly fade out when you click on them, add opacity and transition to the alert class:

Example

// Get all elements with >var close = document.getElementsByClassName(«closebtn»);
var i;

// Loop through all close buttons
for (i = 0; i < close.length; i++) // When someone clicks on a close button
close[i].onclick = function()

// Get the parent of var div = this.parentElement;

// Set the opacity of div to 0 (transparent)
div.style.opacity = «0»;

// Hide the div after 600ms (the same amount of milliseconds it takes to fade out)
setTimeout(function()< div.style.display = "none"; >, 600);
>
>

Tip: Also check out Notes.

Источник

Взаимодействие с пользователем: alert, prompt, confirm

Материал на этой странице устарел, поэтому скрыт из оглавления сайта.

Более новая информация по этой теме находится на странице https://learn.javascript.ru/alert-prompt-confirm.

В этом разделе мы рассмотрим базовые UI операции: alert , prompt и confirm , которые позволяют работать с данными, полученными от пользователя.

alert

alert выводит на экран окно с сообщением и приостанавливает выполнение скрипта, пока пользователь не нажмёт «ОК».

Окно сообщения, которое выводится, является модальным окном. Слово «модальное» означает, что посетитель не может взаимодействовать со страницей, нажимать другие кнопки и т.п., пока не разберётся с окном. В данном случае – пока не нажмёт на «OK».

prompt

Функция prompt принимает два аргумента:

result = prompt(title, default);

Она выводит модальное окно с заголовком title , полем для ввода текста, заполненным строкой по умолчанию default и кнопками OK/CANCEL.

Читайте также:  Multiple CSS Classes on a Single Element

Пользователь должен либо что-то ввести и нажать OK, либо отменить ввод кликом на CANCEL или нажатием Esc на клавиатуре.

Вызов prompt возвращает то, что ввёл посетитель – строку или специальное значение null , если ввод отменён.

Единственный браузер, который не возвращает null при отмене ввода – это Safari. При отсутствии ввода он возвращает пустую строку. Предположительно, это ошибка в браузере.

Если нам важен этот браузер, то пустую строку нужно обрабатывать точно так же, как и null , т.е. считать отменой ввода.

Как и в случае с alert , окно prompt модальное.

var years = prompt('Сколько вам лет?', 100); alert('Вам ' + years + ' лет!')

Второй параметр может отсутствовать. Однако при этом IE вставит в диалог значение по умолчанию «undefined» .

Запустите этот код в IE, чтобы понять о чём речь:

Поэтому рекомендуется всегда указывать второй аргумент:

confirm

confirm выводит окно с вопросом question с двумя кнопками: OK и CANCEL.

Результатом будет true при нажатии OK и false – при CANCEL( Esc ).

var isAdmin = confirm("Вы - администратор?"); alert( isAdmin );

Особенности встроенных функций

Конкретное место, где выводится модальное окно с вопросом – обычно это центр браузера, и внешний вид окна выбирает браузер. Разработчик не может на это влиять.

С одной стороны – это недостаток, так как нельзя вывести окно в своём, особо красивом, дизайне.

С другой стороны, преимущество этих функций по сравнению с другими, более сложными методами взаимодействия, которые мы изучим в дальнейшем – как раз в том, что они очень просты.

Это самый простой способ вывести сообщение или получить информацию от посетителя. Поэтому их используют в тех случаях, когда простота важна, а всякие «красивости» особой роли не играют.

Резюме

  • alert выводит сообщение.
  • prompt выводит сообщение и ждёт, пока пользователь введёт текст, а затем возвращает введённое значение или null , если ввод отменён (CANCEL/ Esc ).
  • confirm выводит сообщение и ждёт, пока пользователь нажмёт «OK» или «CANCEL» и возвращает true/false .

Источник

Window: alert() method

window.alert() instructs the browser to display a dialog with an optional message, and to wait until the user dismisses the dialog.

Under some conditions — for example, when the user switches tabs — the browser may not actually display a dialog, or may not wait for the user to dismiss the dialog.

Syntax

Parameters

A string you want to display in the alert dialog, or, alternatively, an object that is converted into a string and displayed.

Return value

Examples

.alert("Hello world!"); alert("Hello world!"); 

Black alert dialog box. At the top left small circle icon follow by white open and close brackets containing this white text: JavaScript application. Below on the left, a Hello world! white text. And on the bottom right a small blue button. The button

Notes

The alert dialog should be used for messages which do not require any response on the part of the user, other than the acknowledgement of the message.

Читайте также:  Python readline all file

Dialog boxes are modal windows — they prevent the user from accessing the rest of the program’s interface until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box (or modal window).

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 8, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Взаимодействие: alert, prompt, confirm

Так как мы будем использовать браузер как демо-среду, нам нужно познакомиться с несколькими функциями его интерфейса, а именно: alert , prompt и confirm .

alert

С этой функцией мы уже знакомы. Она показывает сообщение и ждёт, пока пользователь нажмёт кнопку «ОК».

Это небольшое окно с сообщением называется модальным окном. Понятие модальное означает, что пользователь не может взаимодействовать с интерфейсом остальной части страницы, нажимать на другие кнопки и т.д. до тех пор, пока взаимодействует с окном. В данном случае – пока не будет нажата кнопка «OK».

prompt

Функция prompt принимает два аргумента:

result = prompt(title, [default]);

Этот код отобразит модальное окно с текстом, полем для ввода текста и кнопками OK/Отмена.

title Текст для отображения в окне. default Необязательный второй параметр, который устанавливает начальное значение в поле для текста в окне.

Квадратные скобки вокруг default в описанном выше синтаксисе означают, что параметр факультативный, необязательный.

Пользователь может напечатать что-либо в поле ввода и нажать OK. Введённый текст будет присвоен переменной result . Пользователь также может отменить ввод нажатием на кнопку «Отмена» или нажав на клавишу Esc . В этом случае значением result станет null .

Вызов prompt возвращает текст, указанный в поле для ввода, или null , если ввод отменён пользователем.

let age = prompt('Сколько тебе лет?', 100); alert(`Тебе $ лет!`); // Тебе 100 лет!

Второй параметр является необязательным, но если не указать его, то Internet Explorer вставит строку «undefined» в поле для ввода.

Запустите код в Internet Explorer и посмотрите на результат:

Чтобы prompt хорошо выглядел в IE, рекомендуется всегда указывать второй параметр:

confirm

Функция confirm отображает модальное окно с текстом вопроса question и двумя кнопками: OK и Отмена.

Результат – true , если нажата кнопка OK. В других случаях – false .

let isBoss = confirm("Ты здесь главный?"); alert( isBoss ); // true, если нажата OK

Итого

Мы рассмотрели 3 функции браузера для взаимодействия с пользователем:

alert показывает сообщение. prompt показывает сообщение и запрашивает ввод текста от пользователя. Возвращает напечатанный в поле ввода текст или null , если была нажата кнопка «Отмена» или Esc с клавиатуры. confirm показывает сообщение и ждёт, пока пользователь нажмёт OK или Отмена. Возвращает true , если нажата OK, и false , если нажата кнопка «Отмена» или Esc с клавиатуры.

Все эти методы являются модальными: останавливают выполнение скриптов и не позволяют пользователю взаимодействовать с остальной частью страницы до тех пор, пока окно не будет закрыто.

Читайте также:  Index php component user login

На все указанные методы распространяются два ограничения:

  1. Расположение окон определяется браузером. Обычно окна находятся в центре.
  2. Визуальное отображение окон зависит от браузера, и мы не можем изменить их вид.

Такова цена простоты. Есть другие способы показать более приятные глазу окна с богатой функциональностью для взаимодействия с пользователем, но если «навороты» не имеют значения, то данные методы работают отлично.

Источник

JavaScript Message Boxes: alert(), confirm(), prompt()

JavaScript provides built-in global functions to display popup message boxes for different purposes.

  • alert(message): Display a popup box with the specified message with the OK button.
  • confirm(message): Display a popup box with the specified message with OK and Cancel buttons.
  • prompt(message, defaultValue): Display a popup box to take the user’s input with the OK and Cancel buttons.

In JavaScript, global functions can be accessed using the window object like window.alert() , window.confirm() , window.prompt() .

alert()

The alert() function displays a message to the user to display some information to users. This alert box will have the OK button to close the alert box.

The alert() function takes a paramter of any type e.g., string, number, boolean etc. So, no need to convert a non-string type to a string type.

alert("This is an alert message box."); // display string message alert('This is a numer: ' + 100); // display result of a concatenation alert(100); // display number alert(Date()); // display current date 

confirm()

Use the confirm() function to take the user’s confirmation before starting some task. For example, you want to take the user’s confirmation before saving, updating or deleting data.

bool window.confirm([message]);

The confirm() function displays a popup message to the user with two buttons, OK and Cancel . The confirm() function returns true if a user has clicked on the OK button or returns false if clicked on the Cancel button. You can use the return value to process further.

The following takes user’s confirmation before saving data:

var userPreference; if (confirm("Do you want to save changes?") == true) < userPreference = "Data saved successfully!"; > else < userPreference = "Save Cancelled!"; > 

prompt()

Use the prompt() function to take the user’s input to do further actions. For example, use the prompt() function in the scenario where you want to calculate EMI based on the user’s preferred loan tenure.

string prompt([message], [defaultValue]);

The prompt() function takes two parameters. The first parameter is the message to be displayed, and the second parameter is the default value in an input box.

var name = prompt("Enter your name:", "John"); if (name == null || name == "") < document.getElementById("msg").innerHTML = "You did not entert anything. Please enter your name again"; > else < document.getElementById("msg").innerHTML = "You enterted: " + name; > 

Источник

Оцените статью