2013-08-25 46 views
0

我遇到了一些麻煩,我的嵌套for循環。我試圖確定在我的表單中選中複選框的值。有人告訴我,整個事情應該格式化像這樣:未捕獲的類型錯誤:對象沒有方法'setAttribute'

for(checkboxes loop){ 
    for(item.appointmentType[1] loop){ 
     if(statement conditional){ 
      set checks code 
     } 
    } 
} 

但我只是似乎無法得到它正確地寫,因爲我收到一個錯誤說, 遺漏的類型錯誤:對象沒有方法「的setAttribute」

下面是我正在使用的代碼。有人可以幫我糾正它,可能知道我在說什麼嗎?

var checkboxes = document.forms[0].appointmentType; 
for(var i=0; i<checkboxes.length; i++){ 
    for(var j=0; j<item.appointmentType[1].length; j++){ 
     if(checkboxes[i].value === item.appointmentType[1][j]){ 
     item.appointmentType[1][j].setAttribute("checked", "checked"); 
     } 
    } 
} 

這裏是與JavaScript一起使用的HTML代碼。所有的JavaScript都包含在它自己的.js文件中。

<ul><span class="lab"> 
<li><input type="checkbox" checked value="Get A Free Estimate" id="Get A Free Estimate" 
    name="appointmentType" /><label for="getAFreeEstimate"><span class="gfe">Get A FREE 
    Estimate</span></label></li> 
<li><input type="checkbox" value=" Lawn Service" id="lawnService" name="appointmentType"/ 
    <label for="lawnService"><span class="ls">Lawn Service</span></label></li> 
<li><input type="checkbox" value=" Sprinkler System Service" id="sprinklerSystemService" 
    name="appointmentType" /><label for="sprinklerSystemService"><span 
    class="sss">Sprinkler System Service</span></label></li> 
<li><input type="checkbox" value=" Flower Bed Maintenance" id="flowerBedMaintenance" 
    name="appointmentType" /><label for="flowerBedMaintenance"><span class="fbm">Flower 
    Bed Maintenance</span></label></li> 
<li><input type="checkbox" value=" Hedge/Tree Service" id="hedgeTreeService" 
    name="appointmentType" /><labe for="hedgeTreeService"><span class="hts">Hedge/Tree 
    Service</span></label></li> 
<li><input type="checkbox" value=" Handyman Services" id="handymanServices" 
    name="appointmentType" /><label for="handymanServices"><span class="hs">Handyman 
    Services</span></label></li> 
<li><input type="checkbox" value=" Other" id="other" name="appointmentType" /><label 
    for="other"><span class="otr">Other</span></label></li></span></ul><br/> 
+0

「item」應該如何得到一個值? – Pointy

+0

您可以顯示與此代碼一起使用的HTML嗎? – Barmar

回答

0

這條線:

item.appointmentType[1][j].setAttribute("checked", "checked"); 

也許應該是:

checkboxes[i].checked = true; 
+0

嘿,這似乎工作沒有任何錯誤。謝謝。現在我只是提交它進行審批,看看它是否正確。謝謝。 – user2704668

+0

謝謝你,誰給了我這個答案。這是正確的,沒有任何錯誤的工作很好。 – user2704668

0

如果您的Jquery在您的proyect渲染認爲你可以取代你行:

複選框= $('input [type =「checkbox」]'); (checkboxes [i])。prop('checked',true);

也許會幫助

+0

for循環需要如上所述進行格式化。如果你願意,可以把它寫出來,這樣我就可以看到你描述的究竟是什麼。謝謝。 – user2704668

相關問題