How to check a checkbox using javascript?
I have set of images and checkboxes like below
<form name="food_type_form method="post" action="proc.php">
<img src="images/type_indian.jpg" alt="Select Indian food" />
<input type="checkbox" name="food_type[]" value="indian" />Indian
<img src="images/type_chinese.jpg" alt="Select Chinese food" />
<input type="checkbox" name="food_type[]" value="chinese" />Chinese
<img src="images/type_japanese.jpg" alt="Select Japanese food" />
<input type="checkbox" name="food_type[]" value="japanese" />Japanese / Sushi
<a href="#" onclick="document.food_type_form.submit()">Show Restaurants >></a>
</form>
When the image is clicked i want to CHECK the checkbox below that image. If the checkboxes have different name we can do it with document.myform.box1.checked = true;
But how to check if it is a set of checkbox
Edit 1
NOTE : <LABEL>
will not work, as i want to submit the form on image cli开发者_如何学Gock.
Wrap the image in a label element.
If you use a <label>
, the default behavior is to invoke the action of it's child, so you can simple wrap each one, like this:
<label>
<img src="images/type_indian.jpg" alt="Select Indian food" />
<input type="checkbox" name="food_type[]" value="indian" />Indian
</label>
Give it a try here, this allows clicking the image, the checkbox or the text for selection, making it even more usable.
You will need the "label" element, for this example & your code should be like:-
<form name="food_type_form method="post" action="proc.php">
<label for="indian">
<img src="images/type_indian.jpg" alt="Select Indian food" />
<input type="checkbox" name="food_type[]" id="indian" value="indian" />Indian
</label>
<label for="chinese">
<img src="images/type_chinese.jpg" alt="Select Chinese food" />
<input type="checkbox" name="food_type[]" id="chinese" value="chinese" />Chinese
</label>
<label for="japanese">
<img src="images/type_japanese.jpg" alt="Select Japanese food" />
<input type="checkbox" name="food_type[]" id="japanese" value="japanese" />Japanese / Sushi
</label>
<a href="#" onclick="document.food_type_form.submit()">Show Restaurants >></a>
</form>
Hope it helps.
精彩评论