我试图在选中两个复选框组时接收它们的值。但是,如果我更改这些组的检索顺序,我将无法接收数据。
HTML:
<div class="btn-group" data-toggle="buttons">//Hai
<p>CheckBox Group1:</p>
<input type="checkbox" name="hai" value="option1" onClick="cbChanged(this);">option 1
<input type="checkbox" name="hai" value="option2" onClick="cbChanged(this);">option 2
</div>
<div class="btn-group" data-toggle="buttons">//Hello
<p>CheckBox Group2:</p>
<input type="checkbox" name="hello" value="option3" onClick="cbChanged(this);">option 3
<input type="checkbox" name="hello" value="option4" onClick="cbChanged(this);">option 4
</div>
JS:
//Gets hit when a checkbox has been checked/unchecked
cbChanged = function (checkboxElem)
{
getSelectedCB();
}
//Called by above function
function getSelectedCB()
{
var result = "";
//Gets value from checkbox group hai
var c1 = getcb1();
alert(c1);
//Gets value from checkbox group hello
var c2 = getcb2();
alert(c2);
result=c1+c2;
alert(result);
}
//gets value from checkbox group hai
function getcb1()
{
var res="";
var cb1 = getCheckedBoxes("hai");
for (var i = 0; i < cb1.length; i++)
{
res = res + cb1[i].value + "+";
}
return res;
}
//gets value from checkbox group hello
function getcb2()
{
var res="";
var cb2 = getCheckedBoxes("hello");
for (var i = 0; i < cb2.length; i++)
{
res = res + cb2[i].value + "+";
}
return res;
}
//Function to gets the values
function getCheckedBoxes(chkboxName)
{
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i = 0; i < checkboxes.length; i++)
{
// And stick the checked ones onto an array...
if (checkboxes[i].checked)
{
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
问题:
当我在复选框组 1[hai] 之前选择复选框组 2[Hello] 时,我无法接收数据。但是当我在“Hello”之前选择“hai”时,我能够接收数据。
如果我犯了一些愚蠢的错误,请多多包涵。