FlashNews!

How to Get the Value of Text Input Field Using JavaScript

In this tutorial, you will learn about getting the value of the text input field using JavaScript. There are several methods are used to get an input textbox value without wrapping the input element inside a form element. Let’s show you each of them separately and point the differences.

The first method uses document.getElementById(‘textboxId’).value to get the value of the box:

document.getElementById("inputId").value;
html> html> head> title>Title of the Document title> head> body> input type="text" placeholder="Type " id="inputId"> button type="button" onclick="getInputValue();">Get Value button> script> function getInputValue( ) < // Selecting the input element and get its value let inputVal = document.getElementById("inputId").value; // Displaying the value alert(inputVal); > script> body> html>

You can also use the document.getElementsByClassName(‘className’)[wholeNumber].value method which returns a Live HTMLCollection. HTMLCollection is a set of HTM/XML elements:

document.getElementsByClassName("inputClass")[0].value;
html> html> head> title>Title of the Document title> head> body> input type="text" placeholder="Type " id="inputId" class="inputClass"> button type="button" onclick="getInputValue();">Get Value button> script> function getInputValue( ) < // Selecting the input element and get its value let inputVal = document.getElementsByClassName("inputClass")[0].value; // Displaying the value alert(inputVal); > script> body> html>

Or you can use document.getElementsByTagName(‘tagName’)[wholeNumber].value which is also returns a Live HTMLCollection:

document.getElementsByTagName("input")[0].value;

Live HTMLCollection only includes the matching elements (e.g. class name or tag name) and does not include text nodes.

Читайте также:  Php сумма двух переменных

Another method is document.getElementsByName(‘name’)[wholeNumber].value which returns a live NodeList which is a collection of nodes. It includes any HTM/XML element, and text content of a element:

document.getElementsByName("searchText")[0].value;

Use the powerful document.querySelector(‘selector’).value which uses a CSS selector to select the element:

document.querySelector('#searchText').value; // selected by id document.querySelector('.search_Field').value; // selected by class document.querySelector('input').value; // selected by tagname document.querySelector('[name="searchText"]').value; // selected by name

There is another method document.querySelectorAll(‘selector’)[wholeNumber].value which is the same as the preceding method, but returns all elements with that selector as a static Nodelist:

document.querySelectorAll('#searchText')[0].value; // selected by id document.querySelectorAll('.search_Field')[0].value; // selected by class document.querySelectorAll('input')[0].value; // selected by tagname document.querySelectorAll('[name="searchText"]')[0].value; // selected by name

Nodelist and HTMLCollection

The HTMLCollection represents a generic collection of elements in document order suggesting methods and properties to select from the list. The HTMLCollection in the HTML DOM is live, meaning when the document is changed it will be automatically updated. NodeList objects are collections of nodes returned by properties such as Node. There are two types of NodeList: live and static. It is static when any change in the DOM does not affect the content of the collection. And live when the changes in the DOM automatically update the collection. You can loop over the items in a NodeList using a for loop. Using for. in or for each. in is not recommended.

Источник

Input Text value Property

The value property sets or returns the value of the value attribute of a text field.

The value property contains the default value OR the value a user types in (or a value set by a script).

Browser Support

Syntax

Return the value property:

Property Values

Technical Details

More Examples

Example

Get the value of a text field:

Example

var at = document.getElementById(«email»).value.indexOf(«@»);
var age = document.getElementById(«age»).value;
var fname = document.getElementById(«fname»).value;
submitOK = «true»;

if (fname.length > 10) alert(«The name may have no more than 10 characters»);
submitOK = «false»;
>

if (isNaN(age) || age < 1 || age >100) alert(«The age must be a number between 1 and 100»);
submitOK = «false»;
>

if (at == -1) alert(«Not a valid e-mail!»);
submitOK = «false»;
>

if (submitOK == «false») return false;
>

Example

var mylist = document.getElementById(«myList»);
document.getElementById(«favorite»).value = mylist.options[mylist.selectedIndex].text;

Example

var no = document.getElementById(«no»);
var option = no.options[no.selectedIndex].text;
var txt = document.getElementById(«result»).value;
txt = txt + option;
document.getElementById(«result»).value = txt;

Example

An example that shows the difference between the defaultValue and value property:

Источник

Получаем данные из поля ввода с помощью input.value

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

Адрес e-mail добавлен в список получателей рассылки.

Адрес электронной почты в сообщении должен быть тем, который введёт пользователь. Как его получить?

Нам поможет особое свойство, которое есть у полей ввода, — value . Допустим, на странице есть поле ввода input :

Босс проходил мимо и ввёл туда своё имя — Кекс. С помощью свойства value мы можем получить данные из этого поля ввода. А после, например, вывести их в консоль:

let input = document.querySelector('input'); console.log(input.value); // Выведет: Кекс

А ещё мы можем вывести данные из поля ввода прямо на страницу. Представим, что у нас на странице есть абзац, который мы нашли и сохранили в переменную paragraph . Мы можем сделать так:

paragraph.textContent = input.value;

И теперь то, что ввёл пользователь в поле input , отобразится на странице как текстовое содержимое элемента paragraph .

В нашем случае пользователь вводит свой адрес в поле с классом subscription-email . Найдём его и скажем JavaScript вывести полученные данные на страницу.

Почему бы не прочитать текст из поля ввода с помощью textContent ? Если мы попытаемся это сделать, то получим пустую строку. Для JavaScript поля формы не имеют текстового содержимого, их значения хранятся именно в value .

Хотите всё и сразу? HTML, CSS, JavaScript, React, Node.js, оплачиваемая стажировка в Лиге А и гарантия трудоустройства. Записывайтесь на профессию «Фулстек-разработчик», которая стартует 5 сентября 2023. Всего от 5 250 ₽ в месяц.

На главную

email

Новая библиотека для создания графиков

Теперь вы можете создать дашборд за считанные секунды.

Что там у роботов?

В робототехнике происходит много интересного, эта новость могла бы быть об этом, но нет.

© FlashNews!

let page = document.querySelector(‘.page’); let themeButton = document.querySelector(‘.theme-button’); themeButton.onclick = function() < page.classList.toggle('light-theme'); page.classList.toggle('dark-theme'); >; let message = document.querySelector(‘.subscription-message’); let form = document.querySelector(‘.subscription’); // Объявите переменную здесь form.onsubmit = function(evt) < evt.preventDefault(); // Измените значение textContent на следующей строке message.textContent = 'Форма отправлена!'; >;

Спасибо! Мы скоро всё исправим)

Источник

How to Get the Value of Text Input Field Using JavaScript

In this tutorial, you will learn about getting the value of the text input field using JavaScript. There are several methods are used to get an input textbox value without wrapping the input element inside a form element. Let’s show you each of them separately and point the differences.

The first method uses document.getElementById(‘textboxId’).value to get the value of the box:

document.getElementById("inputId").value;
html> html> head> title>Title of the Document title> head> body> input type="text" placeholder="Type " id="inputId"> button type="button" onclick="getInputValue();">Get Value button> script> function getInputValue( ) < // Selecting the input element and get its value let inputVal = document.getElementById("inputId").value; // Displaying the value alert(inputVal); > script> body> html>

You can also use the document.getElementsByClassName(‘className’)[wholeNumber].value method which returns a Live HTMLCollection. HTMLCollection is a set of HTM/XML elements:

document.getElementsByClassName("inputClass")[0].value;
html> html> head> title>Title of the Document title> head> body> input type="text" placeholder="Type " id="inputId" class="inputClass"> button type="button" onclick="getInputValue();">Get Value button> script> function getInputValue( ) < // Selecting the input element and get its value let inputVal = document.getElementsByClassName("inputClass")[0].value; // Displaying the value alert(inputVal); > script> body> html>

Or you can use document.getElementsByTagName(‘tagName’)[wholeNumber].value which is also returns a Live HTMLCollection:

document.getElementsByTagName("input")[0].value;

Live HTMLCollection only includes the matching elements (e.g. class name or tag name) and does not include text nodes.

Another method is document.getElementsByName(‘name’)[wholeNumber].value which returns a live NodeList which is a collection of nodes. It includes any HTM/XML element, and text content of a element:

document.getElementsByName("searchText")[0].value;

Use the powerful document.querySelector(‘selector’).value which uses a CSS selector to select the element:

document.querySelector('#searchText').value; // selected by id document.querySelector('.search_Field').value; // selected by class document.querySelector('input').value; // selected by tagname document.querySelector('[name="searchText"]').value; // selected by name

There is another method document.querySelectorAll(‘selector’)[wholeNumber].value which is the same as the preceding method, but returns all elements with that selector as a static Nodelist:

document.querySelectorAll('#searchText')[0].value; // selected by id document.querySelectorAll('.search_Field')[0].value; // selected by class document.querySelectorAll('input')[0].value; // selected by tagname document.querySelectorAll('[name="searchText"]')[0].value; // selected by name

Nodelist and HTMLCollection

The HTMLCollection represents a generic collection of elements in document order suggesting methods and properties to select from the list. The HTMLCollection in the HTML DOM is live, meaning when the document is changed it will be automatically updated. NodeList objects are collections of nodes returned by properties such as Node. There are two types of NodeList: live and static. It is static when any change in the DOM does not affect the content of the collection. And live when the changes in the DOM automatically update the collection. You can loop over the items in a NodeList using a for loop. Using for. in or for each. in is not recommended.

Источник

HTML DOM Input Text Object

The Input Text object represents an HTML element with type=»text».

Access an Input Text Object

You can access an element with type=»text» by using getElementById():

Example

Tip: You can also access by searching through the elements collection of a form.

Create an Input Text Object

You can create an element with type=»text» by using the document.createElement() method:

Example

Input Text Object Properties

Property Description
autocomplete Sets or returns the value of the autocomplete attribute of a text field
autofocus Sets or returns whether a text field should automatically get focus when the page loads
defaultValue Sets or returns the default value of a text field
disabled Sets or returns whether the text field is disabled, or not
form Returns a reference to the form that contains the text field
list Returns a reference to the datalist that contains the text field
maxLength Sets or returns the value of the maxlength attribute of a text field
name Sets or returns the value of the name attribute of a text field
pattern Sets or returns the value of the pattern attribute of a text field
placeholder Sets or returns the value of the placeholder attribute of a text field
readOnly Sets or returns whether a text field is read-only, or not
required Sets or returns whether the text field must be filled out before submitting a form
size Sets or returns the value of the size attribute of a text field
type Returns which type of form element a text field is
value Sets or returns the value of the value attribute of the text field

Input Text Object Methods

Method Description
blur() Removes focus from a text field
focus() Gives focus to a text field
select() Selects the content of a text field

Standard Properties and Events

The Input Text object also supports the standard properties and events.

Источник

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