Alert var value in javascript

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

Читайте также:  Модуль string python методы

Вызов 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 .

Источник

Alert var value in javascript

Last updated: Feb 27, 2023
Reading time · 4 min

banner

# Table of Contents

# Display a Variable value in an Alert box in JavaScript

You can use the addition (+) operator to display a variable value in an alert box.

The addition operator will concatenate the alert message and the variable and will display the entire string.

Here is an example HTML page that loads a JavaScript index.js file.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div>bobbyhadz.comdiv> script src="index.js"> script> body> html>

And here is the code for the index.js file.

Copied!
const fullName = 'Bobby Hadz'; alert('Employee name: ' + fullName);

using variable in alert box addition operator

You can use this approach to concatenate the alert message with as many variables as necessary.

Copied!
const first = 'Bobby'; const last = 'Hadz'; alert('Employee name: ' + first + ' ' + last);

using variable in alert box addition operator

# Display a Variable value in an Alert box using a template literal

An alternative approach is to use a template literal.

Note that template literal strings are enclosed in backticks «, not in single quotes.

Copied!
const first = 'Bobby'; const last = 'Hadz'; alert(`Employee name: $first> $last>`);

using variable in alert box addition operator

You can use the dollar sign $<> curly braces syntax to interpolate variables in the alert message.

Make sure to use backticks « and not single quotes when wrapping the alert message for the template string to work as expected.

# Displaying an Object or an Array in an Alert box

If you try to display an object or an array of objects in an alert box, you’d get an » [object Object] » value back.

Copied!
const obj = id: 1, name: 'Bobby Hadz', age: 30, >; alert(obj);

display object without json stringify

The » [object Object] » value is not very useful.

The alert() function tries to convert the object to a string and prints » [object Object] «.

You can use the JSON.stringify() method to print the actual value of the object.

Copied!
const obj = id: 1, name: 'Bobby Hadz', age: 30, >; alert(JSON.stringify(obj));

alert object value with json stringify

The JSON.stringify method converts a JavaScript value to a JSON string.

If you need to print a message and an object or array variable, use a template literal.

Copied!
const obj = id: 1, name: 'Bobby Hadz', age: 30, >; alert(`Employee object: $JSON.stringify(obj)>`);

alert object variable and message

# Display multiple variables in an Alert box, on separate lines

If you need to display variables in an Alert box on separate lines, use a template literal.

Copied!
const first = 'Bobby'; const last = 'Hadz'; const age = 30; alert(`First Name: $first> Last Name: $last> Age: $age>`);

display multiple variables on separate lines

New lines are preserved when using template literals, so you can just write your alert message spanning multiple lines.

Note that template literals are enclosed in backticks « and not single quotes.

# Displaying an Alert with a variable on button click

Let’s look at an example of displaying an alert with a variable on button click.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div>bobbyhadz.comdiv> button id="btn">Clickbutton> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const fullName = 'Bobby Hadz'; const button = document.getElementById('btn'); button.addEventListener('click', event => alert('Name: ' + fullName); >);

We added a click event listener to the button, so every time it’s clicked, we call the alert() function with a message and a variable.

# Alert with a variable on button click without external JavaScript file

Alternatively, you can add the onclick event listener online, in your HTML code to not have to write your JavaScript separately.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> script> const fullName = 'BobbyHadz'; function myFunction() alert('Name: ' + fullName); > script> head> body> div>bobbyhadz.comdiv> button id="btn" onclick="myFunction()">Clickbutton> body> html>

The code sample achieves the same result without using an external JavaScript file.

# Displaying an Alert with variables from Form input fields

Let’s look at an example of displaying variables from form fields using the alert() function.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div>bobbyhadz.comdiv> form id="form"> input type="text" id="first" placeholder="First name: " /> input type="text" id="last" placeholder="Last name: " /> button id="btn" type="submit">Submitbutton> form> script src="index.js"> script> body> html>

Here is the related JavaScript code.

Copied!
const form = document.getElementById('form'); form.addEventListener('submit', event => event.preventDefault(); const first = document.getElementById('first').value; const last = document.getElementById('last').value; if (first.trim() === '' || last.trim() === '') alert('The fields are required.'); > else alert(`Name: $first> $last>`); > >);

We used the event.preventDefault() function to prevent the page refresh when the form is submitted.

We selected the first and last input fields and accessed their values.

The last step is to call the alert() function with the message and the variables.

The function uses an if/else statement to alert the user that the fields are required if they forget to enter a value.

# Displaying an Alert with variables from Form input fields without external JavaScript

You can achieve the same result without an external JavaScript file, by using an inline event listener.

Here is the HTML and JavaScript code for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> script> function alertFormValues() const form = document.getElementById('form'); const first = document.getElementById('first').value; const last = document.getElementById('last').value; if (first.trim() === '' || last.trim() === '') alert('The fields are required.'); > else alert(`Name: $first> $last>`); > > script> head> body> div>bobbyhadz.comdiv> form id="id" onsubmit="alertFormValues()"> input type="text" id="first" placeholder="First name: " /> input type="text" id="last" placeholder="Last name: " /> button id="btn" type="submit">Submitbutton> form> body> html>

We wrote the JavaScript code in a script tag, so no external JS code is loaded.

The code alerts the input fields value from the form without using any external JavaScript files.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to display a variable value using JavaScript alert dialog

JavaScript provides you with the alert() method that allows you to create an alert box, where you can display some information together with an OK button to remove the alert.

You can test the alert() method by simply opening your browser’s console and type in alert() as in the screenshot below:

JavaScript alert dialog in the browser

The alert() method is also useful for testing your JavaScript code and see if a certain variable holds the right value. For example, you may have the isMember variable that contains true if the user has logged in to your website and false when the user is not.

You can use the alert() method to print the value of the variable as follows:

The result would be as follows:

JavaScript alert displaying variable

Be aware that the alert() method can’t print an array of objects as follows:

 The above code will cause the alert box to display [Object object] as in the screenshot below:

JavaScript alert can

To prevent this issue, you need to transform the array of objects into a JSON string first using the JSON.stringify() method:

 Now the alert box will display the values without any trouble:

JavaScript alert displaying stringified objects

And that’s how you can use the alert() method to display variable values.

You can use the alert() method to display multiple variables too, just like a normal string. It’s recommended for you to use template string to ember the variables in your alert box as follows:

[email protected]"       The result in the browser will be similar to this:

JavaScript alert displaying multiple variables

Feel free to use the alert() call above as you require it 😉

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

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