- How to Get the Value of Text Input Field Using JavaScript
- Nodelist and HTMLCollection
- Input Text value Property
- Browser Support
- Syntax
- Property Values
- Technical Details
- More Examples
- Example
- Example
- Example
- Example
- Example
- Получаем данные из поля ввода с помощью input.value
- How to Get the Value of Text Input Field Using JavaScript
- Nodelist and HTMLCollection
- HTML DOM Input Text Object
- Access an Input Text Object
- Example
- Create an Input Text Object
- Example
- Input Text Object Properties
- Input Text Object Methods
- Standard Properties and Events
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.
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 ₽ в месяц.