Working with checkbox in PHP and JS
I am creating a form with both radio buttons and checkboxe开发者_JS百科s. I want to validate the form with both javascript onsubmit, and php. For php to work, I have to write the checkboxes and radiobuttons with [] in the name (e.g. ) I searched the other topics and saw that I can put a default checked value for radiobuttons to avoid the probably of people not picking a value. That's fine. However, I also need to make sure people check no more than 3 check boxes. This cannot be done with
var count = 0;
for (x=0; x<document.fic_rec.rec_genre.length; x++){
if (document.fic_rec.rec_genres[x].checked){
count++;
}
}
if (count==0){
rec_error += "at least 1 genre; ";
}
else if (count>3){
rec_error += "no more than 3 genres; ";
}
I get an error saying "Cannot read property 'length' of undefined My HTML code looks like this:
<ul class="sub_ul">
<li class="sub">
<input type="checkbox" name="rec_genres[]" id="action"value="action" />
<label for="action">Action/Adventure</label></span><li class="sub"><u>Alternative reality</u></li>
<li class="sub_sub"><input type="checkbox" name="rec_genres[]" id=au_history value="au_history" />
<label for="au_history">AU History</label></li><li class="sub_sub"><input type="checkbox" name="rec_genres[]" id=au_universe value="au_universe" />
<label for="au_universe">AU Universe</label></li><li class="sub_sub"><input type="checkbox" name="rec_genres[]" id=au_other value="au_other" />
etc etc
Help! Thanks!!
Use e.g. the elements-collection to access those elements:
document.fic_rec.elements['rec_genres[]']
Please note:
This will return a nodeList if there are more than 1 element found.
If there is only 1 element with the given name, it will return the element itself and not a nodeList.
You may also use querySelectorAll()
(not supported by IE<8)
document.querySelectorAll('form[name="fic_rec"] input[name="rec_genres[]"]')
...this will always return a nodeList, no matter how many elements are found.
Answer to the comment:
var radio_count = 0;
for (var i=0;i<document.fic_rec.elements['rec_pub_length[]'].length;i++)
{
if (document.fic_rec.elements['rec_pub_length[]'][i].checked)
{
radio_count = 1;
break;
}
}
if (radio_count != 1) { rec_error += "story length; "; }
精彩评论