I wanna get the total number of the checkbox in a html.
request: (1) By Javascript (2) all my checkbox id is "id=idCheckBox", (3) each checkbox name is reserved for back-end using. not for javascript. (4) The naming for each checkbox's name is like checkbox_1, checkbox_2,... where the number indicate the serial number of a checkbox.
The Table Html
<table class="form_table" border="0" cellpadding="0" width="750px" id="idRoutineListTable">
<tr>
<td style="align:center;" class="routineListCell">
<input type='checkbox' name='checkbox_1' id='idCheckBox'></input>
<!-- It may many checkbox here.-->
</td>
</tr>
</table>
My JS code, the function is to check any checkbox is selected before deletion. if no checkbox is selected, it pops up warning.
function beforeDelete() /*{{{*/
{
var checked=0;
var checkboxAll=document.all["idCheckBox"];
//the开发者_运维知识库 error is here, when there is only one checkbox, I cannot get length value,
//coz checkboxAll is not recognized as an array. However, if there are more than
//two checkboxes, the function works.
alert (checkboxAll.length);
for(var i=0;i<checkboxAll.length;i++) {
if (checkboxAll[i].checked==true) {
checked++;
}
}
if(checked==0) {
alert('Please select the item you will delete');
return false;
}
} /*}}}*
The problem has indicate in the above code. Any idea to solve this?
here is a full working sample using jQuery:
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script>
function beforeDelete() {
if ($("input:checked").length == 0) {
alert('Please select the item you will delete');
return false;
}
return true;
}
</script>
<form onsubmit="return beforeDelete()">
<table class="form_table" border="0" cellpadding="0" width="750px" id="idRoutineListTable">
<tr>
<td style="align:center;" class="routineListCell">
<input type='checkbox' name='checkbox_1' id='idCheckBox'></input>
<input type='checkbox' name='checkbox_2' id='idCheckBox'></input>
<input type='checkbox' name='checkbox_3' id='idCheckBox'></input>
<!-- It may many checkbox here.-->
</td>
</tr>
</table>
<input type="submit" />
</form>
Try this:
function beforeDelete() {
var checkboxAll=document.getElementsByTagName("input");
for(var i=0;i<checkboxAll.length;i++) {
var input = checkboxAll[i];
if (input.type == "checkbox" && input.checked==true) {
return true;
}
}
alert('Please select the item you will delete');
return false;
}
The first decision: You may use checkboxAll.length as a condition to check if there is only one checkbox in your markup.
if(checkboxAll.length == undefined)
If not, you may use your code with loop, if it is only one checkbox - check only one.
The second decision: To use getElementsByTag that will return you an array. In this case you need to filter this array with the given id
Demo for both decisions here
精彩评论