Javascript form element this

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.

Источник

Using JavaScript to access form objects when there are multiple forms

In order to access a form through JavaScript, we need to obtain a reference to the form object. One obvious way to approach, is to use the getElementById method. For instance, if we had a form with the id attribute «subscribe_frm» , we could access the form in this way:

var oForm = document.getElementById('subscribe_frm'); 

However, this approach has the limitation that the tag must have an id attribute, as the getElementById method needs the id of an element in order to locate it in the DOM tree. Fortunately, JavaScript provides us with alternatives where you can get the form when you don’t have the id attribute.

One way to approach is to make use of the this keyword which always points to the object that is calling a particular method. Used in conjunction with the onClick event handler of a form’s submit button, we can get a reference to the form itself, through the this.form property, even if there are multiple forms on the page.

The other alternative is to use the document object’s forms collection to obtain a reference to the form object. The forms collection is a JavaScript array that holds references to all the forms present in a web page. We can access each form reference either by it’s index in this array or by it’s name attribute. Let us look at each of these methods of accessing multiple forms in details.

Accessing the form object through JavaScript using the this.form property

Every element in a form triggers events based on user action which can be handled by an appropriate event handler. For instance, the submit button on being clicked triggers the onClick event handler. Since the ‘this’ keyword in JavaScript always points to the object that calls a given method, the onClick event handler can be passed ’this’ self reference to obtain a reference to the button element object.

Moreover, in JavaScript, every element object of a form has a property that references the form object. So, if we were to pass this.form to the onClick event handler of a form button, this function would get the reference to the form object. This is an easy way to access form objects, even if there are multiple forms on a web page, because the form’s name or id attribute are never directly used. Let us have a look at an example.

 form name ="submit_bookmark" action="#">  Page Title: input type="text" name="page_title" size="50">  Page URL: label>input type="text" name="page_url" size="50">  Tags (comma separated): input type="text" name="tags_list" size="40">  input type="button" name="submit" value="Save Bookmark" onclick="showElements(this.form);">  form>  

In the form above, the showElements onClick event handler of the form button is being passed this.form . Here this refers to the button object, and this.form references the form object. We could now use this form object in the showElements function and access the form and all it’s elements.

Have a look at this demo which shows two form on a web page. You can also download the code.

Accessing multiple Forms using the document object’s forms collection

The document object of a web page has a property named forms which is a JavaScript array that holds references to all the form objects on the page. We can get a reference to individual forms by using the index of the forms or by using their names. Please note that this array’s index begins at 0.

For instance, if we have two forms “submit_article” and “submit_bookmark” appearing on a web page in this order, we can access the form named “submit_bookmark” in the following two ways:

var oForm = document.forms[1]; 
var oForm = document.forms["submit_bookmark"]; 

We can use the same approach to access individual form elements as well. Every form field of a form is contained in the form’s elements collection which is a JavaScript array similar to the document object’s forms collection.

To access the text input field named “tags_list” of the form named “submit_bookmark” (which was the second form on the web page, as you saw in the demo), we can use one of the following methods:

var oForm = document.forms["submit_bookmark"]; 
 var oTagsList = oForm.elements[2]; OR var oTagsList = oForm.elements["tags_list"]; 

Please have a look at this detailed demo to understand the concepts presented. Download the code.

Example: Copy from one form to other

Let us say that we had to copy the value of an element in one form into an element in another form. Have a look at this demo.

We could implement this by passing the names of the two forms as well as the names of the source and target elements to a javascript function:

 a href="#" onClick=" javascript: copyFormElementToElementOfDifferentForm('submit_article', 'submit_bookmark', 'site_cat', 'tags_list');">Copy site_cat element value of the first form to the input field named "tags_list" of the second forma>  

Have a look at the implementation of this function:

 var oForm1 = document.forms[oForm1Name]; var oForm2 = document.forms[oForm2Name]; var oForm1Element = oForm1[oForm1ElementName]; var oForm2Element = oForm2[oForm2ElementName]; if (oForm2Element.value == '')   oForm2Element.value += oForm1Element.value; > else   oForm2Element.value += ', ' + oForm1Element.value; > 

We first acquire references to form objects using their names. We then acquire references to the source and target elements, again using the element names. Thereafter, it is an easy job to copy the value of the source element to the target element.

See Also

Источник

Читайте также:  Registration Form
Оцените статью