Current course:

Javascript - getting <form> element values

First, lets create a form with all of the different form element types:

<form name="myForm">
      What is your name?<br />
      <input type="text" name="theName" value=""><br /><br />

      Do you like pizza?<br />
      <input type="radio" name="pizza" value="yes"> Yes<br />
      <input type="radio" name="pizza" value="no"> No<br /><br />

      With what toppings?<br />
      <input type="checkbox" name="toppings" value="mushrooms"> Mushrooms<br />
      <input type="checkbox" name="toppings" value="olives"> Olives<br />
      <input type="checkbox" name="toppings" value="chicken"> Chicken<br /><br />

      How many pizzas do you want?<br />
      <select name="numPizzas" ><br />
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="47">47</option>
      </select><br /><br />

       <input type="submit" name="submit" value="submit">

<a href="javascript: alertText();">ALERT TEXT</a><br />
<a href="javascript: alertRadio();">ALERT RADIO BUTTONS</a><br />
<a href="javascript: alertCheckbox();">ALERT CHECK BOXES</a><br />
<a href="javascript: alertSelect();">ALERT SELECT</a><br />

Then, we add the javascript in the head:

<script type="text/javascript">
      function alertText() {
            var theValue = document.myForm.theName.value;

      function alertRadio() {
            for (var i=0; i <; i++) {
                  if ([i].checked) {
                        var theValue =[i].value;

      function alertCheckbox() {
            var theValue = "";
            for (var i=0; i < document.myForm.toppings.length; i++) {
                  if (document.myForm.toppings[i].checked) {
                        theValue = theValue + document.myForm.toppings[i].value + "\n";

//the selectedIndex is the number of the item that is selected in the pulldown menu. You can also use select.text to get the actual text of the item in the list that was chosen.
      function alertSelect() {
            var select = document.myForm.numPizzas;
            var theValue = select.options[select.selectedIndex].value;


Instead of using alert to echo back the value, how else could you use the information?


Click for an example of the form in action