User input alert javascript

How to alert input value

So I recently decided to try learning app development with Intel XDK, and as of now I know only little bit of HTML. I’m trying to create a basic test app that allows the user to type a message in a text box, and then click the submit button which gives an alert that displays the inputted text. This is what I have:

5 Answers 5

to get an element value use

var message = document.getElementById("message").value; alert( message ); 

Also, don’t use inline JS. Rather assign an event handler

document.getElementById("myButton").addEventListener("click", function() < var message = document.getElementById("message").value; alert( message ); >, false); 

Here’s a working example:

var message = document.getElementById("message"); document.getElementById("myButton").addEventListener("click", function() < console.log( message.value ); >);

But when I run the app it displays «[object HTMLInputElement]». How do I fix this?

message at html , javascript references element having id «message» . You are calling alert() with DOM element #message as parameter. To correct this you can pass .value property of #message : message to alert(message.value) .

You could alternatively attach a click event to button element and call alert(document.getElementById(«message»)) within click handler, as demonstrated by @RokoC.Buljan solution.

You are missing quotes around alert() at onclick , and .value at message

Источник

Взаимодействие: 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 с клавиатуры.

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

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

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

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

Источник

Взаимодействие с пользователем: 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.

Пользователь должен либо что-то ввести и нажать 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 .

Источник

Interaction: alert, prompt, confirm

As we’ll be using the browser as our demo environment, let’s see a couple of functions to interact with the user: alert , prompt and confirm .

alert

This one we’ve seen already. It shows a message and waits for the user to press “OK”.

The mini-window with the message is called a modal window. The word “modal” means that the visitor can’t interact with the rest of the page, press other buttons, etc, until they have dealt with the window. In this case – until they press “OK”.

prompt

The function prompt accepts two arguments:

result = prompt(title, [default]);

It shows a modal window with a text message, an input field for the visitor, and the buttons OK/Cancel.

title The text to show the visitor. default An optional second parameter, the initial value for the input field.

The square brackets around default in the syntax above denote that the parameter is optional, not required.

The visitor can type something in the prompt input field and press OK. Then we get that text in the result . Or they can cancel the input by pressing Cancel or hitting the Esc key, then we get null as the result .

The call to prompt returns the text from the input field or null if the input was canceled.

let age = prompt('How old are you?', 100); alert(`You are $ years old!`); // You are 100 years old!

The second parameter is optional, but if we don’t supply it, Internet Explorer will insert the text «undefined» into the prompt.

Run this code in Internet Explorer to see:

So, for prompts to look good in IE, we recommend always providing the second argument:

confirm

The function confirm shows a modal window with a question and two buttons: OK and Cancel.

The result is true if OK is pressed and false otherwise.

let isBoss = confirm("Are you the boss?"); alert( isBoss ); // true if OK is pressed

Summary

We covered 3 browser-specific functions to interact with visitors:

alert shows a message. prompt shows a message asking the user to input text. It returns the text or, if Cancel button or Esc is clicked, null . confirm shows a message and waits for the user to press “OK” or “Cancel”. It returns true for OK and false for Cancel/ Esc .

All these methods are modal: they pause script execution and don’t allow the visitor to interact with the rest of the page until the window has been dismissed.

There are two limitations shared by all the methods above:

  1. The exact location of the modal window is determined by the browser. Usually, it’s in the center.
  2. The exact look of the window also depends on the browser. We can’t modify it.

That is the price for simplicity. There are other ways to show nicer windows and richer interaction with the visitor, but if “bells and whistles” do not matter much, these methods work just fine.

Источник

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; > 

Источник

Читайте также:  Runtime arguments in java
Оцените статью