I want to know the number of checboxes checked in javascript. If only one checkbox is checked then it should show an alert message, otherwise it should do the processing. I tried if(names[i].checked>2)
but it is not 开发者_如何学运维working.. Please help.
function insert_slide(ed, height, width)
{ var img=new Array();
var names=document.getElementsByName('image_id');
for(i=0;i<names.length;i++)
{
if(names[i].checked)
{
img[i] = "<IMG SRC='" + names[i].value + "'";
if(height != '') {
img[i] += " height='" + height + "'";
}
if(width != '') {
img[i] += " width='" + width + "'";
}
img[i] += " style='margin: 5px;' >";
editor.nicCommand("insertHTML", img[i]);
}}
hide_lightwindow();
}
A solution could be the following:
function check(form) {
var sum = 0;
max = form.box.length;
for(i=0; i<max; i++) {
if(form.box[i].checked) {
sum+=1;
}
}
if (sum==1) {alert("one is checked")}
else {alert("more than one are checked") }
}
Get the lenght
of all chechboxes in a form
. Then check with a for
loop, if there are checked
chechboxes, for each one it finds adds 1
in the variable sum
Demo: http://jsbin.com/ezafal/2
If names contains the checkboxes, this could be a counter:
var countChecked = 0;
for (var i=0;i<names.length;i++){
countChecked += /checkbox/i.test(names[i].type) && names[i].checked ? 1 : 0;
}
if (countChecked === 1) {
// alert something
} else {
// proces
}
So easy with JQuery. You should check into it as your primary JS framework:
if($('input[type=checkbox]:checked').length == 1)
{
alert('Only one checked');
}
else
{
// Do code
}
精彩评论