Set form field javascript

How to set the value of a form element using Javascript

As we have seen in earlier articles, in order to work with forms in JavaScript, it is imperative to obtain references to the form object and its elements. In this article, we will be using the forms collection of the document object and the elements collection of the form object to set the values of the form elements. The syntax for accessing the form object is as below:

oFormObject = document.forms['myform_id']; 

For accessing individual elements, we use the following code:

oformElement = oFormObject.elements[index]; 
oFormElement = oFormObject.elements["element_name"]; 

In the above code, “index” refers to the position of the element in the “elements” collection array, and “element_name” is the name of the element. Both approaches give us a reference to the desired form element.

Setting the value of a textarea element using JavaScript

In order to set the value of a textarea field element in a form, we can use the following code:

oFormObject.elements["element_name"].value = 'Some Value'; 

If we are accessing the form object through any of the form’s elements itself, we can also use the following code:

this.form.elements["element_name"].value = 'Some Value'; 

Let us look at a simple form example.

 form id="register_complaint" action="#">  Full Name: input type="text" size="30" maxlength="155" name="name" />  Email Id: input type="text" size="30" maxlength="155" name="email" />  Service Complaint: textarea name="service_complaint" rows="7" cols="50">textarea>  input type="button" name="submit" value="Submit Complaint" onclick="showElements(this.form);" />  form> 

When the page loads, the textarea field “service_complaint” has a note written for the user: “Please enter your complaint briefly”, but when focus is set to that field, this message disappears, as it should. In order to implement this feature, we would need to write an onLoad event handler for the tag that would set the initial value of the textarea element:

 body onload="initForm(document.forms[0], 'service_complaint', 'Please enter your complaint in brief');"> 

The initForm function could be implemented this way:

 function initForm(oForm, element_name, init_txt)   frmElement = oForm.elements[element_name];  frmElement.value = init_txt; > 

You must have also noticed that this initial message does not re-appear even after the focus is removed and again given to this field. We do this by writing an onFocus event handler for the textarea element. The code below is generic, that can be used for other fields like the text input field as well:

 function clearFieldFirstTime(element)   if(element.counter==undefined)    element.counter = 1;  >  else    element.counter++;  >   if (element.counter == 1)    element.value = '';  > > 

The first time the textarea element is given focus, the property “counter” for the textarea element is not defined, and so we can set the counter, by giving it the initial value 1. Thereafter, on subsequent focus, this counter increments. The value of the textarea is reset only the first time the textarea field gets focus, by setting its value attribute to the empty string.

Setting the value of the text input element through JavaScript

In order to set the value of a text input field element in a form, we can use the following code:

oFormObject.elements["element_name"].value = 'Some Value'; 

Let us look at an example to illustrate how to set the value of the text input element through javascript.

The form in this demo has a “membership_period” text input field that is updated through the use of two JavaScript button elements. Have a look at the way the HTML is coded:

 form id="register_complaint" action="#">  Full Name: input type="text" size="30" maxlength="155" name="name" />  Email Id: input type="text" size="30" maxlength="155" name="email" />  Service Complaint: textarea name="service_complaint" rows="7" cols="50">textarea>  Months as member: input type="text" size="5" maxlength="5" name="membership_period" />  input type="button" name="increase" value="+" onclick="monthModify(this.form.elements["membership_period"], 'incr');" />  input type="button" name="decrease" value="-" onclick="monthModify(this.form.elements["membership_period"], 'decr');" />  input type="button" name="submit" value="Submit Complaint" onclick="showElements(this.form);" />  form> 

As you must have seen in the demo, the text field named “membership_period” has a default value of 6 when the form loads, which can be changed either by directly entering the value in the text input field, or by adjusting the value through the two javascript buttons labeled “+” or “-” . We now need to write a javascript function that can serve as the onClick event handler of the two buttons:

In the function, we would first need to identify which of the two buttons was clicked:

 switch(btnElement.name)  case 'increase':  // code to handle incrementing the value of the  // text input field referenced by txtElement  case 'decrease':  // code to handle decrementing the value of the  // text input field referenced by txtElement  > 

For the case ‘increase’, we would need to check if the value we are trying to increment is an integer, and if it is, then we increment it:

 case 'increase':  if(isEmpty(txtElement.value))    txtElement.value = '1';  >  else if(isInteger(txtElement.value))    txtElement.value ++;  >  else    alert('The value you are trying to increment is not a number');  txtElement.value = '';  >  break; 

The function isEmpty() checks whether the value of the text input field is empty or not, and the function isInteger() checks if the value is an integer. If all these tests return true, we increment the value using the construct: txtElement.value ++. Have a look at the code sample for the implementation of these functions.

For the case ‘decrease’ the code is very similar; have a look at the code sample.

See Also

Источник

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

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

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

Формы в документе входят в специальную коллекцию 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 , которые могут происходить на любом элементе, но чаще всего обрабатываются в формах.

Источник

Читайте также:  Php curl get response status
Оцените статью