Asim Zaidi
Asim Zaidi

Reputation: 28284

checkbox value is not displaying

I have the following code

   <tr>
<td align=left colspan=6><table border="0">
  <tr>
      <td><font class="body_text"> windows: <input name="pro1" id="products0" type="checkbox" value="5" test="5"></td>

        <td><font class="body_text"> cpu: <input name="pro2" id="products1" type="checkbox" value="2" test="2"></td>

        <td><font class="body_text"> keyboard: <input name="pro3" id="products2" type="checkbox" value="3" test="3"></td>

        <td><font class="body_text"> mouse: <input name="pro4" id="products3" type="checkbox" value="4" test="4"></td>


  </tr>

and I am trying to get the value of first check box in the DOM

if(document.form.products[0].checked == true) alert(document.form.products[0].value);

this gives me an alert but value is undefined.

thanks

Upvotes: 0

Views: 175

Answers (2)

Quentin
Quentin

Reputation: 943579

Assuming that the controls are in a form with the id form (which isn't a good name), then the problem is that you don't have any controls with the name "products", but you are trying to access a control with that name.

Either change products to the name (or id) of the control you want (and since the names are unique, get rid of [0]) or change the names of all the checkboxes to products.

You also have a number of other problems which aren't directly related to this issue.

  1. You are using <font> which is deprecated, presentational and rubbish
  2. You aren't using <label> which is needed for accessibility (including making the click target for checkboxes bigger than tiny)
  3. You appear to be are using tables for layout
  4. form is too generic an id
  5. Better style is document.form.ID_OF_FORM.elements.NAMES_OF_CHECKBOXES[0]
  6. The checked property is a boolean, == true is redundant

Upvotes: 1

Phrogz
Phrogz

Reputation: 303253

You have all your inputs with the same id attribute. This is syntactically illegal and also likely the cause of your trouble. Make each one unique.

Upvotes: 0

Related Questions