Javascript复选框

时间:2011-07-09 14:38:24

标签: javascript

我想知道在javascript中检查的checbox的数量。如果仅选中一个复选框,则应显示警告消息,否则应执行处理。我试过了if(names[i].checked>2)但它没有用..请帮助。

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();
}

3 个答案:

答案 0 :(得分:0)

使用JQuery这么容易。您应该将其作为主要JS框架进行检查:

if($('input[type=checkbox]:checked').length == 1)
{
    alert('Only one checked');
}
else
{
    // Do code
}

答案 1 :(得分:0)

如果名称包含复选框,则可以是计数器:

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
}

答案 2 :(得分:0)

解决方案可能如下:

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") }
}

获取lenght中所有chechbox的form。然后使用for循环检查,如果有checked个cheboxbox,则会在变量1

中添加sum

演示: http://jsbin.com/ezafal/2