Problem with default checked checkboxes: Javascript
I have created the following function to check the first value of the check box when loading a page -
function defaultCheck(){
document.checkBoxForm.list[0].checked = true;
var val=document.checkBoxForm.list[0].value;
showtotal[0] = document.checkBoxForm.list[0].value;
show(val);
editVal();
//alert('ajhsdjha');
}
I have used the function in html page load by <body onload="defaultCheck()">
.
My problem is - when there are more than one values in the list the function by default selects the first one but when there is just one value in the开发者_StackOverflow list, it does not select it. The values of check boxes are dynamically retrieved from database by -
<?php
while($row=mysql_fetch_array($levelq)) {?>
<input type='checkbox' name="list" value="<?=$row['tag']?>"
id="<?=$row['tag']?>" onclick="" />
<? echo $row['tag'].' '.'<br/><br/>';
}
?>
I have no idea why is it behaving so weird. Can anyone help me out please?
I'll bet money that the problem is the use of [0]
. Have you considered removing that?
But, that said, you shouldn't be doing this in JS anyway, you should do this in PHP:
$checked = 'checked="true"';
while($row=mysql_fetch_array($levelq)) {
// you also may wish to consider using list[] instead of list. That will make
// reading the value much easier in PHP
?>
<input type='checkbox' name="list" value="<?=$row['tag']?>"
id="<?=$row['tag']?>" onclick="" <?=$checked?> />
<? echo $row['tag'].' '.'<br/><br/>';
$checked = "";
}
Like @cwallenpoole said, you should be doing this in PHP.
If you still want to do it in JS, here you go:
function defaultCheck(){
if(document.checkBoxForm.list.length > 1) {
document.checkBoxForm.list[0].checked = true;
var val=document.checkBoxForm.list[0].value;
showtotal[0] = document.checkBoxForm.list[0].value;
} else {
document.checkBoxForm.list.checked=true;
var val=document.checkBoxForm.list.value;
showtotal[0] = document.checkBoxForm.list.value;
}
show(val);
editVal();
//alert('ajhsdjha');
}
This happens because, when there is only 1 checkbox, list refers to that checkbox, NOT the array of checkboxes
精彩评论