Javascript form input value by name

Form properties and methods

Forms and control elements, such as have a lot of special properties and events.

Working with forms will be much more convenient when we learn them.

Document forms are members of the special collection document.forms .

That’s a so-called “named collection”: it’s both named and ordered. We can use both the name or the number in the document to get the form.

document.forms.my; // the form with name="my" document.forms[0]; // the first form in the document

When we have a form, then any element is available in the named collection form.elements .

    

There may be multiple elements with the same name. This is typical with radio buttons and checkboxes.

In that case, form.elements[name] is a collection. For instance:

    

These navigation properties do not depend on the tag structure. All control elements, no matter how deep they are in the form, are available in form.elements .

A form may have one or many elements inside it. They also have elements property that lists form controls inside them.

  
info

There’s a shorter notation: we can access the element as form[index/name] .

In other words, instead of form.elements.login we can write form.login .

That also works, but there’s a minor issue: if we access an element, and then change its name , then it is still available under the old name (as well as under the new one).

That’s easy to see in an example:

   

That’s usually not a problem, however, because we rarely change names of form elements.

Backreference: element.form

For any element, the form is available as element.form . So a form references all elements, and elements reference the form.

   

Form elements

Let’s talk about form controls.

input and textarea

We can access their value as input.value (string) or input.checked (boolean) for checkboxes and radio buttons.

input.value = "New value"; textarea.value = "New text"; input.checked = true; // for a checkbox or radio button

Please note that even though holds its value as nested HTML, we should never use textarea.innerHTML to access it.

It stores only the HTML that was initially on the page, not the current value.

select and option

A element has 3 important properties:

  1. select.options – the collection of subelements,
  2. select.value – the value of the currently selected ,
  3. select.selectedIndex – the number of the currently selected .

They provide three different ways of setting a value for a :

  1. Find the corresponding element (e.g. among select.options ) and set its option.selected to true .
  2. If we know a new value: set select.value to the new value.
  3. If we know the new option number: set select.selectedIndex to that number.

Here is an example of all three methods:

  

Unlike most other controls, allows to select multiple options at once if it has multiple attribute. This attribute is rarely used, though.

For multiple selected values, use the first way of setting values: add/remove the selected property from subelements.

Here’s an example of how to get selected values from a multi-select:

   

new Option

In the specification there’s a nice short syntax to create an element:

option = new Option(text, value, defaultSelected, selected);

This syntax is optional. We can use document.createElement(‘option’) and set attributes manually. Still, it may be shorter, so here are the parameters:

  • text – the text inside the option,
  • value – the option value,
  • defaultSelected – if true , then selected HTML-attribute is created,
  • selected – if true , then the option is selected.

The difference between defaultSelected and selected is that defaultSelected sets the HTML-attribute (that we can get using option.getAttribute(‘selected’) , while selected sets whether the option is selected or not.

In practice, one should usually set both values to true or false . (Or, simply omit them; both default to false .)

For instance, here’s a new “unselected” option:

let option = new Option("Text", "value"); // creates 

The same option, but selected:

let option = new Option("Text", "value", true, true);

Option elements have properties:

option.selected Is the option selected. option.index The number of the option among the others in its . option.text Text content of the option (seen by the visitor).

References

Summary

document.forms A form is available as document.forms[name/index] . form.elements Form elements are available as form.elements[name/index] , or can use just form[name/index] . The elements property also works for . element.form Elements reference their form in the form property.

Value is available as input.value , textarea.value , select.value , etc. (For checkboxes and radio buttons, use input.checked to determine whether a value is selected.)

For , one can also get the value by the index select.selectedIndex or through the options collection select.options .

These are the basics to start working with forms. We’ll meet many examples further in the tutorial.

In the next chapter we’ll cover focus and blur events that may occur on any element, but are mostly handled on forms.

Источник

Получить значение value из тега input | JavaScript

document.getElementById() — поиск по тегу с атрибутом id

id на веб-странице может быть присвоен только один раз одному тегу HTML Задача: нужно вывести значение выбранного цвета рядом с полем ввода:

idColor" placeholder="введите текст"/> rezultatColor">  

document.getElementsByName() — поиск по NodeList тегов с атрибутом name

Задача: прибавить значение только третьего включенного чекбокса, округлить до сотых и показать в формате 0.00 (с двумя знаками после запятой):
1.00

name="nameCheckbox" value="1"/> name="nameCheckbox" value="20"/> name="nameCheckbox" value="300.555" onclick="onclickCheckbox()"/> name="nameCheckbox" value="400"/> 1.00  Пояснения: имеется четыре тега input с name="nameCheckbox". [0] - это первый по счёту, соответственно, [2] будет третьим.
nameRadio" value="1" checked="checked"/> nameRadio" value="20"/> nameRadio" value="300"/> nameRadio" value="400"/> 1  

document.getElementsByClassName() — поиск по NodeList тегов с атрибутом class

 .classGreen < background: green; width: 130px; height: 130px; margin: 0 auto; transition: .5s; >.classRed 
class="classGreen">

document.body — поиск по тегу body

document.body.innerHTML = document.body.innerHTML.replace(/\u003Ch2/g, '\u003Ch3');" /> Пояснения: я меняю , потому что тег может содержать атрибуты.  пишу как специальный символ в JavaScript \u003C.

document.getElementsByTagName() — поиск по NodeList тегов

h3')[4].innerHTML = 'Скрипт сработал\(\)'"/> Скрипт сработал\(\) - это то, на что мы заменяем наш текст. Он выглядит как Скрипт сработал(). Куда же делись символы \? Они реализуют экранирование скобок, чтобы те были рассмотрены как текстовые символы, а не как код скрипта. 
 Li(); setInterval(Li,1000); function Li() < d = new Date(); var month=new Array("января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря"); var week=new Array("воскресенье","понедельник","вторник","среда","четверг","пятница","суббота"); document.getElementById('d').getElementsByTagName('li')[0].innerHTML='Дата: '+d.getDate()+' '+month[d.getMonth()]+' '+d.getFullYear()+' года, '+week[d.getDay()]; document.getElementById('d').getElementsByTagName('li')[1].innerHTML='Время: '+((d.getHours()

document.querySelector() — поиск по селектору

Задача: показать степень заполнения полей, пароль и email должен быть внесён правильно.
Почта
Пароль

 input:focus:invalid < border: 1px solid #eee; >input:invalid Почта  
Пароль " title="Не менее 6 знаков, в том числе хотя бы одна цифра и буква" onchange="oninputEmail()"/>
0%

document.querySelectorAll() — поиск по NodeList селекторов

Помните этот пример? Там поиск идёт только по h3. Именно на него произойдет замена по этой кнопке. Если её не нажимать, то скрипт не будет работать. А вот так будет и при h2, и при h3

h2, h3')[4].innerHTML = 'Скрипт сработал\(\)'"/>

11 комментариев:

Анонимный Здравствуйте!
У меня вот такой вопрос. Не подскажите.
Есть 2 поля и две кнопки.
Я хочу VALUE кнопок передать в поля.

Просто значение например 1 кнопки передать в 1 поле понятно. Но хотелось бы. Что бы в поле попадало значение кнопки которую нажал. Не важно 1 или 2 или 11.

Вот что-то начал но дальше…

form
input type=»text» value=»1″
input type=»text» value=»2″
/form

input name=»poga2″ type=»button» value=»L» onclick=»q.value = fun()»
input name=»poga3″ type=»button» value=»M»

script
function fun() var per1=document.getElementById(‘q’).value;
var per2=document.getElementById(‘x’).value;

/script
Буду очень благодарен за подсказку.
До свидания.
NMitra Здравствуйте, пример http://jsfiddle.net/NMitra/dhj7epc4/

Анонимный Здравствуйте!
Спасибо Вам за ответ. Спасибо за помощь.
Анонимный Здравствуйте!
Подскажите как перебрать список с помощью javascript :
ul
li1/li
li2/li
li3/li
li4/li
li5/li
li6/li
li7/li
/ul

script
var el = document.querySelector(‘li’);

Источник

Get HTML Form Value in JavaScript

Get HTML Form Value in JavaScript

  1. Use the document.forms to Get HTML Form Value in JavaScript
  2. Use the id to Access HTML Form Value in JavaScript

In JavaScript, we can use a specific input element’s id attribute to get the values or trigger the name attribute to access the values.

Both of the conventions will proceed to fetch the raw data from the user. Technically, the target is to grab all the input from a user and ensure the process is working.

Here we will work with the HTML DOM aka document.forms to retrieve all the elements from the HTML form . A brief introduction to the methods available to interact with the HTML elements and attributes is here.

Also, in our example, we will use the casual way of identifying the id of an element to draw out the information from there.

Use the document.forms to Get HTML Form Value in JavaScript

The document.forms method takes the name attribute to locate the form and its element. Tactically, all values from the form will be passed through this way of initiation.

We will have a select element followed by a multiple option element. And we will choose a preference from there, and the value will be separated.

Later, when the document.forms will be initiated, it will grab the separated value. Let’s check the code block for proper visualization.

 html> head>  meta charset="utf-8">  meta name="viewport" content="width=device-width">  title>Testtitle>  head> body> form name="form"> select name="fruit" id="fruits">  option value="0">Select Fruitoption>  option value="mango">Mangooption>  option value="apple">Appleoption>  option value="orange">Orangeoption>  select>  button type = "submit">Hitbutton>  form>  p id="print">p>  body>  html> 

Источник

Читайте также:  Css stylesheet screen width
Оцените статью