2011-03-30 44 views
1

我正在嘗試迭代每個文本輸入字段,並確定是否選中了分配給它的複選框。儘管我在選擇each()循環內的複選框時遇到了困難。在每個()循環中選中複選框時遇到問題

我的HTML:

<table> 
     <tbody> 
       <tr> 
        <td style="vertical-align: top;"> 
         <label for="MainTemplate" class="">Hlavná šablóna:</label> 
        </td> 
        <td> 
         <input name="MainTemplate" class="input mainTemplate" value="" style="width: 10em;" type="text"> <br> <table> 

    <tbody><tr>   <td>   <input name="MainTemplateInheritCheckbox" class="input inheritCheckbox" value="1" checked="checked" type="checkbox">  </td>  <td style="font-size: 0.9em;">   <label for="MainTemplateInheritCheckbox">hodnoda sa zdedí z vyššej úrovne</label>  </td> </tr> 

</tbody></table> 
         <br> 
        </td> 
       </tr> 
       <tr> 
        <td style="vertical-align: top;"> 
         <label for="Lector" class="">Školiteľ:</label> 
        </td> 
        <td> 

         <input name="Lector" class="input lector" value="" style="width: 10em;" type="text"> <br> <table> <tbody><tr>   <td>   <input name="LectorInheritCheckbox" class="input inheritCheckbox" value="1" checked="checked" type="checkbox">  </td>  <td style="font-size: 0.9em;">   <label for="LectorInheritCheckbox">hodnoda sa zdedí z vyššej úrovne</label> 

     </td> </tr> </tbody></table> 
         <br> 
        </td> 
       </tr> 
</table> 

我的jQuery代碼:

 $("input[type=text]").each(function() { 
      // here I need to find out whether the checkbox is checked or not 
     }); 

我試過,但即使選中的複選框返回false:

alert($(this).next().next().children("input[type=checkbox]:first").is(":checked")); 

回答

3

嘗試$(this).next('table').find('input[type=checkbox]:first')is(':checked');

你可能也可以通過名字得到它,因爲它們是相關的。

var cbName = '#' + $(this).attr('name') + 'InheritCheckbox'; 
$(cbName).is(':checked'); 

這兩者都是一點點脆弱和依賴無論是在DOM或元素名稱之間的關係,雖然我懷疑後者可能是隨着時間的推移更加穩定。

+0

權。該複選框是通過調用'next'兩次獲得的節點的後代,但不是直接的子節點。你(=理查德)也可以用你的原始代碼中的'find'代替'children',儘管'.next()。next()'在我看來像是要求麻煩,如果你的HTML結構變化甚至有點小位。 – 2011-03-30 12:18:22

2

試試這個(獲得含錶行並搜索元素中的複選框):

$("input[type=text]").each(function() { 
    alert($(this).closest("tr").find("input[type=checkbox]:first").is(":checked")); 
}); 
1

嘗試

$("input[type=checkbox]:first",$(this).parent()).is(":checked") 

jsFiddle

1
$("input[type=text]").each(function() 
{ 
    alert($(this).closest("td").find("input[type=checkbox]").attr("checked")); 
}); 
相關問題