2011-01-07 23 views
0

我有這些尷尬的複選框和unfortunatley我不能重命名他們同樣由於其他編碼的原因....我怎麼能得到選中的複選框的值。如何獲取複選框在尷尬的情況下的價值

<tr> 
    <td align=left colspan=6> 
     <table border="0"> 
     <tr> 
      <td><font class="body_text"> windows: <input name="pro1" id="products0" type="checkbox" value="5" test="5"></td> 
      <td><font class="body_text"> cpu:  <input name="pro2" id="products1" type="checkbox" value="2" test="2"></td> 
      <td><font class="body_text"> keyboard: <input name="pro3" id="products2" type="checkbox" value="3" test="3"></td> 
      <td><font class="body_text"> mouse: <input name="pro4" id="products3" type="checkbox" value="4" test="4"></td> 
     </tr> 

我使用下面的代碼,在alret

if(document.form.pro1.checked) 
    alert(document.getElementById('products0').value); 
+0

你打的Javascript一些onclick事件? – Naved 2011-01-07 07:29:29

+0

你得到了什麼確切的錯誤?哪裏?什麼時候?另外,你也可以發佈'

`。 form是form的名字嗎? – Nivas 2011-01-07 07:39:17

回答

2

給你內心的表中的ID,然後...

myTable=document.getElementById('mytable'); 
var inputArray=myTable.getElementsByTagName('input'); 
for(var i=0;i<inputArray.length;i++){ 
    if(inputArray[i].type=='checkbox' && inputArray[i].checked==true){ 
    alert(inputArray[i].value); 
} 
    } 
0

返回undefined是有一些原因,你不能只是做

alert(document.form.pro1.value); 
+0

我想他可能只想獲得所選複選框 – Naved 2011-01-07 08:40:53

0

你爲什麼不使用jQuery獲取值?

$(document).ready(function() { 
    var checkboxValues = Array(); 

    $("form#idOfForm").submit(function() { 
     $("form input:checkbox:checked").each(function() { 
      checkboxValues.push($(this).val()); // alternative use checkboxValues.push($(this).attr("value")); if this doesn't work 
     }); 
    }); 
}); 

請確保首先包含jQuery庫。

0

假設你只有4複選框和他們所有的ID以「產品」

var cboxId = 'products'; 

for(var i=0;i<4;i++){ 

    if (document.getElementById(cboxId +i).checked == true){ <br> 
     // add to some array or call some functions to do checked processing 
    } 

}