Reading and Setting Form Elements

Once your form and form elements have names, JavaScript can easily find out what your visitors have typed into the form elements. Just tell JavaScript the form and element for which you want information.

Reading Information from Text Fields

If you want to see what value a user has typed into the text field named the_age_field (❷) in Figure 7-12, use this:

window.document.my_form.the_age_field.value

This line tells JavaScript to look in the window, locate its document, find the form called my_form inside the document, find the form element called the_age_field inside that form, and read its value. Figure 7-16 shows how to build a simple calculator using form elements as inputs.

Figure 7-16. A very simple calculator ...

Get The Book of JavaScript, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.