- How to set the value of a form element using Javascript
- Setting the value of a textarea element using JavaScript
- Setting the value of the text input element through JavaScript
- See Also
- Form properties and methods
- Navigation: form and elements
- Backreference: element.form
- Form elements
- input and textarea
- select and option
- new Option
- References
- Summary
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
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.
Navigation: form and elements
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.
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:
- select.options – the collection of subelements,
- select.value – the value of the currently selected ,
- select.selectedIndex – the number of the currently selected .
They provide three different ways of setting a value for a :
- Find the corresponding element (e.g. among select.options ) and set its option.selected to true .
- If we know a new value: set select.value to the new value.
- 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.