开发者

losing variables from javascript array when passing to php

I'm trying to implement a page with a choice of user's preferences in an HTML form where if the checkbox ALL is selected then all sub-checkbox base1, base2 and base3 are checked automatically, and if any of sub-checkboxes is un-selected then the checkbox ALL must be unchecked. I used a javascript function which works but when I submit the form only the last variable in the array of checkboxes is sent.

<SCRIPT LANGUAGE="JavaScript">       
function checkChoice(field, i) {

if (i == 0) { // "All" checkbox selected.
if(field[0].checked==true) {
for (i = 1; i < field.length; i++)
field[i].checked = true;
   }
}
else  {  
if (field[i].checked == false) {
field[0].checked = false;
      }
   }
}

<form name="form" method = "POST" action="preferences.php">

<i开发者_如何学运维nput type=checkbox name=classes1 value="allbases" onclick="checkChoice(document.form.classes1, 0)">All bases
</td><td>
<input type=checkbox name=classes1 value="base1" onclick="checkChoice(document.form.classes1, 1)">Base1
<br>
<input type=checkbox name=classes1 value="base2" onclick="checkChoice(document.form.classes1, 2)">Base2
<br>
<input type=checkbox name=classes1 value="base3" onclick="checkChoice(document.form.classes1, 3)">Base3
<input type="submit"  value="Set preferences" >  

If I call the checkboxes'names in "classes1[]" all the values are submited but the javascript function doesn't work anymore. Is there a way of fixing this? Thanks for any help.


For an alternative of checkChoice: check this SO question and the jsfiddle I presented there.

[edit] concerning your comment: a bit of extra thinking would have brought you to this solution


All of the values actually ARE submitted but PHP will overwrite $_POST['classes1'] each time until you are just left with the last value. If however you add '[]' to your input names then they are added to an array.

Since the latter causes a problem with javascript, can you not just either a) iterate all of the form elements from the form.elements array, or b) give each input a unique id and use document.getElementById() to find it?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜