Select input value in javascript

Свойства и методы формы

Формы и элементы управления, такие как , имеют множество специальных свойств и событий.

Работать с формами станет намного удобнее, когда мы их изучим.

Формы в документе входят в специальную коллекцию document.forms .

Это так называемая «именованная» коллекция: мы можем использовать для получения формы как её имя, так и порядковый номер в документе.

document.forms.my - форма с именем "my" (name="my") document.forms[0] - первая форма в документе

Когда мы уже получили форму, любой элемент доступен в именованной коллекции form.elements .

    

Может быть несколько элементов с одним и тем же именем, это часто бывает с кнопками-переключателями radio .

В этом случае form.elements[name] является коллекцией, например:

    

Эти навигационные свойства не зависят от структуры тегов внутри формы. Все элементы управления формы, как бы глубоко они не находились в форме, доступны в коллекции form.elements .

Форма может содержать один или несколько элементов внутри себя. Они также поддерживают свойство elements , в котором находятся элементы управления внутри них.

  
info

Есть более короткая запись: мы можем получить доступ к элементу через form[index/name] .

Другими словами, вместо form.elements.login мы можем написать form.login .

Это также работает, но есть небольшая проблема: если мы получаем элемент, а затем меняем его свойство name , то он всё ещё будет доступен под старым именем (также, как и под новым).

В этом легче разобраться на примере:

   

Обычно это не вызывает проблем, так как мы редко меняем имена у элементов формы.

Обратная ссылка: element.form

Для любого элемента форма доступна через element.form . Так что форма ссылается на все элементы, а эти элементы ссылаются на форму.

   

Элементы формы

Рассмотрим элементы управления, используемые в формах.

input и textarea

К их значению можно получить доступ через свойство input.value (строка) или input.checked (булево значение) для чекбоксов.

input.value = "Новое значение"; textarea.value = "Новый текст"; input.checked = true; // для чекбоксов и переключателей

Обратим внимание: хоть элемент и хранит своё значение как вложенный HTML, нам не следует использовать textarea.innerHTML для доступа к нему.

Там хранится только тот HTML, который был изначально на странице, а не текущее значение.

select и option

Элемент имеет 3 важных свойства:

  1. select.options – коллекция из подэлементов ,
  2. select.value – значение выбранного в данный момент ,
  3. select.selectedIndex – номер выбранного .

Они дают три разных способа установить значение в :

  1. Найти соответствующий элемент и установить в option.selected значение true .
  2. Установить в select.value значение нужного .
  3. Установить в select.selectedIndex номер нужного .

Первый способ наиболее понятный, но (2) и (3) являются более удобными при работе.

Вот эти способы на примере:

  

В отличие от большинства других элементов управления, позволяет нам выбрать несколько вариантов одновременно, если у него стоит атрибут multiple . Эту возможность используют редко, но в этом случае для работы со значениями необходимо использовать первый способ, то есть ставить или удалять свойство selected у подэлементов .

Их коллекцию можно получить как select.options , например:

   

new Option

Элемент редко используется сам по себе, но и здесь есть кое-что интересное.

В спецификации есть красивый короткий синтаксис для создания элемента :

option = new Option(text, value, defaultSelected, selected);
  • text – текст внутри ,
  • value – значение,
  • defaultSelected – если true , то ставится HTML-атрибут selected ,
  • selected – если true , то элемент будет выбранным.

Тут может быть небольшая путаница с defaultSelected и selected . Всё просто: defaultSelected задаёт HTML-атрибут, его можно получить как option.getAttribute(‘selected’) , а selected – выбрано значение или нет, именно его важно поставить правильно. Впрочем, обычно ставят оба этих значения в true или не ставят вовсе (т.е. false ).

let option = new Option("Текст", "value"); // создаст 

Тот же элемент, но выбранный:

let option = new Option("Текст", "value", true, true);

option.selected Выбрана ли опция. option.index Номер опции среди других в списке . option.value Значение опции. option.text Содержимое опции (то, что видит посетитель).

Ссылки

Итого

Свойства для навигации по формам:

document.forms Форма доступна через document.forms[name/index] . form.elements Элементы формы доступны через form.elements[name/index] , или можно просто использовать form[name/index] . Свойство elements также работает для . element.form Элементы хранят ссылку на свою форму в свойстве form .

Значения элементов формы доступны через input.value , textarea.value , select.value и т.д. либо input.checked для чекбоксов и переключателей.

Для элемента мы также можем получить индекс выбранного пункта через select.selectedIndex , либо используя коллекцию пунктов select.options .

Это были основы для начала работы с формами. Далее в учебнике мы встретим ещё много примеров.

В следующей главе мы рассмотрим такие события, как focus и blur , которые могут происходить на любом элементе, но чаще всего обрабатываются в формах.

Источник

HTMLInputElement: select() method

The HTMLInputElement.select() method selects all the text in a element or in an element that includes a text field.

Syntax

Parameters

Return value

Examples

Click the button in this example to select all the text in the element.

HTML

input type="text" id="text-box" size="20" value="Hello world!" /> button onclick="selectText()">Select textbutton> 

JavaScript

function selectText()  const input = document.getElementById("text-box"); input.focus(); input.select(); > 

Result

Notes

Calling element.select() will not necessarily focus the input, so it is often used with HTMLElement.focus .

In browsers where it is not supported, it is possible to replace it with a call to HTMLInputElement.setSelectionRange() with parameters 0 and the input’s value length:

input onClick="this.select();" value="Sample Text" /> input onClick="this.setSelectionRange(0, this.value.length);" value="Sample Text" /> 

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 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Select value Property

The value property sets or returns the value of the selected option in a drop-down list.

Browser Support

Syntax

Return the value property:

Property Values

Value Description
value Specifies the value of an element in a drop-down list that should get selected. If the value does not exist, the drop-down list will display an empty option

Technical Details

Return Value: A String, representing the value of the value attribute of an element in the drop-down list. If the drop-down list allows multiple selections, the first selected option is returned. If there is no selected options, nothing is returned.

More Examples

Example

Return the value of a selected option in a drop-down list:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Get Input Value in JavaScript

Get Input Value in JavaScript

  1. Use document.getElementById(id_name) to Get Input Value in JavaScript
  2. Use document.getElementsByClassName(‘class_name’) to Get Input Value in JavaScript
  3. Use document.querySelector(‘selector’) to Get Input Value in JavaScript

We can get the value of input without wrapping it inside a form element in JavaScript by selecting the DOM input element and use the value property.

JavaScript has different methods for selecting the DOM input element. Every method below will have a code example, which you can run on your machine.

Use document.getElementById(id_name) to Get Input Value in JavaScript

We give the id property to our Dom input element, and then use document.getElementById(id_name) to select DOM input element, you can simply use the value property.

Example:

 html>  body>   h4>  Change the text of the text field  ,and then click the button.  h4>   label for="domTextElement">Name: label>  input type="text" id="domTextElement" >   button type="button" onclick="getValueInput()">  click me!!  button>   p id="valueInput">p>   script>   const getValueInput = () =>  let inputValue = document.getElementById("domTextElement").value;  document.getElementById("valueInput").innerHTML = inputValue;  >  script>  body>  html> 

Use document.getElementsByClassName(‘class_name’) to Get Input Value in JavaScript

We give the class property to our Dom input element, and then use document.getElementsByClassName(‘class_name’) to select DOM input element, but if we have different Dom input elements with the same class name, then it will return an array of Dom inputs, so we should specify which one we will select by giving index number: document.getElementsByClassName(‘class_name’)[index_number].value .

Example:

 html>  body>   h4>  Change the text of the text field  ,and then click the button.  h4>   input type="text" class="domTextElement" >   label for="domTextElement">Name: label>  input type="text" class="domTextElement" >   button type="button" onclick="getValueInput()">  click me!!  button>   p id="valueInput">p>   script>   const getValueInput = () =>  let inputValue = document.getElementsByClassName("domTextElement")[1].value;  document.getElementById("valueInput").innerHTML = inputValue;  >  script>  body>  html> 

Use document.querySelector(‘selector’) to Get Input Value in JavaScript

The document.querySelector(‘selector’) uses CSS selectors which means, it can select elements by id, class, tag name, and name property of the DOM element.

Example:

document.querySelector('class_name') document.querySelector('id_name') document.querySelector('input') //tag name  document.querySelector('[name="domTextElement"]') //name property 

Example:

 html>  body>   h4>  Change the text of the text field  ,and then click the button.  h4>   input type="text" id="domTextElement1" >   label for="domTextElement">Name: label>  input type="text" class="domTextElement2" >   button type="button" onclick="getValueInput()">  click me!!  button>   p id="valueInput">p>   script>   const getValueInput = () =>  let inputValue1 = document.querySelector("#domTextElement1").value;  let inputValue2 = document.querySelector(".domTextElement2").value;  document.querySelector("#valueInput").innerHTML = `First input value: $inputValue1> Second Input Value: $inputValue2>`;  >  script>  body>  html> 

Related Article — JavaScript Input

Copyright © 2023. All right reserved

Источник

Читайте также:  Путь к java bat
Оцените статью