Chapter 8: DOM element Properties

8.4 Interacting with Form Elements

Finally, before we end this chapter, let's move on to learn how we can use Javascript to interact with HTML form elements.

Add the followings lines to DOMProperties.html (after the <body> tag):

<input type = "text" id = "textinput" value = "Hello">

<select id="numbers">
    <option value="">Select One</option>
    <option value="A">Apple</option>
    <option value="G">Grape</option>
    <option value="M">Mango</option>
</select>

This adds a textbox and a dropdown list to our webpage. We can select the textbox and dropdown list using one of the methods covered in Chapter 7.2.

To get the value attribute of the textbox, we use the corresponding value property. Add the following line to chap8.js:

console.log(document.getElementById("textinput").value);

You’ll get

Hello

as the output in the console window.

You can also modify the value property. If you add

document.getElementById("textinput").value = "Hello Again";

to chap8.js and refresh the browser, you’ll see that the text inside the textbox is changed to "Hello Again".

Next, let’s look at the dropdown list. This is a bit more complicated.

In Javascript, all <option> elements of a dropdown list are stored in an array called options. In our example,

options[0] =     <option value="">Select One</option> 
options[1] =     <option value="A">Apple</option>

etc.

To get the value attribute of each <option> element, we use the value property. For instance, if we add

console.log(document.getElementById("numbers").options[1]);
console.log(document.getElementById("numbers").options[1].value);

to chap8.js, we’ll get

    <option value="A">Apple</option>
A

as the output in the console window.

If we want to know which option is being selected, we use the selectedIndex property. If we add

console.log(document.getElementById("numbers").selectedIndex);

To chap8.js, we’ll get

0

as the output.

We can also use the selectedIndex property to set the selected index. If we add

document.getElementById("numbers").selectedIndex = 2;

to chap8.js and refresh the HTML page, we’ll see that the dropdown list now shows “Grape” as the selected option.

Javascript Forms

Clear?