2011-07-09 65 views
1

我想知道在javascript中檢查的checboxes的數量。如果只有一個複選框被選中,那麼它應該顯示一條警告消息,否則它應該執行處理。我試過if(names[i].checked>2),但它不工作..請幫忙。Javascript複選框

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

'名字[I] .checked> 2'將只是一個比較布爾值反對'2',這將始終是錯誤的。你想在'names'中計算'names [i] .checked'爲真的元素...... –

回答

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

獲取form中所有chechbox的lenght。然後用for循環檢查,如果有checked chechboxes,爲每一個找到的變量sum

演示增加1http://jsbin.com/ezafal/2

0

JQuery這麼容易。您應該檢查到它作爲你的主要JS框架:

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

*「使用jQuery」*不是這個問題的答案。這對於普通的JS來說並不是很難...... –

+0

修正你的拼寫,選擇器是':checked',而不是':cheked' :) – Sotiris

+0

「這麼容易」,但卻很慢:http://jsperf.com/ form-traversal-test-speed – 2011-07-09 16:51:53

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 
}