Javascript Guide

Form Manipulation

April 2, 2010

Intro to Forms

Forms are probably the most common way users will interact with your site. Forms are an extensive topic. We can divide HTML forms into design and processing. We will focus on manipulating form fields with Javascript in this section. Form fields can be grouped together into a form element or be single fields all by themselves. Here is a form with fields under a form element.

Note: Form processing occurs on the server side. Once the user clicks on submit, the processing can be done on the server with languages such as PHP or ASP. Only form design and manipulation is covered here. Processing forms is not the scope here.

HTML <form name="formname" method="post" action="submitform.php" > <label>Name</label> <input name="name" id="name" type="text" size="30" value="enter your name" onclick="document.getElementById('name').value = ''; return false ;" /><br/> <label>Age</label> <input id="age" type="text" size="4" /> <label>Weight</label> <input id="weight" type="text" size="4" /> <br/> <input type="submit" class="sumbit" value="Submit" id="Submit" /> <input type="reset" onclick="ResetAll()" id="Clear" value="Clear" /> </form>



Note: Note the use of single quotes and double quotes in the HTML code above. If arguments require to be quoted and are within double quotes, then we use single quotes. Using double quotes within double quotes will cause errors.

In the example above, I have used the name attribute for the form instead of id. Some form fields have both name and id attribute. For submitting the form with PHP, the name attribute may be desired. For manipulating input values, id works better and name is ignored. For example, the initial value of the "Name" input is "enter your name." We want this to be blanked out when user clicks in the field. The onclick="document.getElementById('name').value = ''; makes the field blank. This is where id="name" is required. If you omit this, then the field will not be blanked out.

Common Form Fields

Here are some common form fields and their HTML code:

HTML <label>Text Field: </label> <input id="textfield" size="20" /> <br/> <label>Check Box: </label> <input type="checkbox" id="checkbox" value="myCBValue" checked="checked" /> <br/> <label>Radio button: </label> <input type="radio" name="gender" id="male" value="1" onclick="setGender(this.value)" /> Male <input type="radio" name="gender" id="female" value="0.85" onclick="setGender(this.value)" /> Female <br/> <label>Drop-down: </label> <select id="heightunit" onchange="setHgtFact(this.options[this.selectedIndex].value);"> <option value="1">in</option> <option value="2.54">cm</option> </select> <br/> <label>Button: </label> <input type="button" value="My Button" onclick="action()" />


Male Female

Here are some notes from the HTML code above:

  • If you want the checkbox autochecked on when page loads, include checked="checked" attribute in its input tag.
  • You can pass the value of the self field with this.value to Javascript functions. To pass values of non-self fields, use document.getElementById('myFormField').value
  • For a text field, unless an initial value is specified, it will be null. The value is set after the field is filled by user.
  • For radio buttons, checkboxes, and drop-downs, the value is set with the value= attribute. The value is null until a checkbox is checked, radio button is selected, or an option is selected.
  • Radio buttons can have the same name but have to have different id. This is because you can only select 1 radio button and only the selected radio button's value will be passed to PHP processing.
  • To pass a drop-down value that is selected, use the argument this.options[this.selectedIndex].value.

Form Field Names vs. Form Field Id's

Forms fields can have names and/or id's. You can assign both a name and an id if you wish, depending on what you need to accomplish.

Field names do not have to be unique. Field id's, like all id's, have to be unique. The advantage of assigning a similar name to a group of related fields is being able to apply execute a function to all these fields at once.

In the next pages, you see the advantage of using the same name for grouped fields.

Form Field Values

All form fields can have values. These values can be passed on to Javascript as a variable. The values do not have to be numbers. They can be any string of characters.

For example, for radio buttons for gender (male and female), you can assign a value of 1 to male and 2 to female for whatever purpose.

HTML <input type="radio" id="male" name="gender" value="1" /> <input type="radio" id="female" name="gender" value="0.85" />

In the example above, we have grouped both the radio buttons with the name gender. I have given a value of 1 if male is clicked and 0.85 if female is clicked.

Putting It All Together

The following example calculates the ideal body weight given the person's height and weight.

Height inches
Male Female

Your ideal weight is: ? kg

HTML <table> <tr><td>Height</td> <td><input id="height" type="text" size="4" onchange="setHeight(this.value)" /> inches </td> </tr> <td colspan="2"> <input type="radio" name="gender" id="man" value="50" onchange="setGF(this.value)" /> Male <input type="radio" name="gender" id="woman" value="45" onclick="setGF(this.value)" /> Female </td></tr> </table> <br/> <p>Your ideal weight is: <span id="IBW">?</span> kg</p> Javascript var hgt = null; var gf = null; //gender factor (50 kg for males and 45 kg for females) function setHeight(val) { hgt = val; hgt = hgt * 1; calc_IBW(); } function setGF(val) { gf = val; gf = gf * 1; calc_IBW(); } function calc_IBW() { if (hgt == null || gf == null) { return; } else { var IBW = gf + 2.3*(hgt - 60); IBW_val = IBW.toFixed(1); changeValue('IBW',IBW_val); } }

Notes from above example:

  • I didn't enclose the form input fields in form tag, which is not necessary for this example as we will not be submitting the form values. We are doing a calculation.
  • The event that triggers the Javascript function is onchange. The argument that is passed to the function is this.value which is the value of the self object.
  • In the Javascript, I declared the variables first so that they are global. Making them global will allow the variables to be used by all functions in the Javascript.
  • Notice that I multiplied the height variable with itself by 1 (hgt = hgt * 1;). Reason for doing this is to ensure that the value of the height variable is seen as a number rather than text string. If Javascript sees this variable as text string, then adding it will cause two strings to concatenate instead of mathematical addition. Multiplying the variable by itself with 1 is the easiest way to convert it to a number.
  • Each time height or gender factor is set or changed, those functions call the calc_IBW function. If either value is null, then this function stops executing with return; line.
  • The || is the operator for OR logic.