Jquery:遍历div中的所有标签元素并比较标签以选中复选框

时间:2014-02-16 11:52:51

标签: javascript jquery

    <div id="update-checkbox" class="row update-checkbox" data-company-code="10000005980" data-type="Contractual Customer,Shipper">
        <input type="checkbox" value="2" data-original-title="">
            <div class="span3">
                <label class="checkbox">Contractual Customer<input type="checkbox" value="2" data-original-title=""></label>
            </div>
            <div class="span3">
                <label class="checkbox">Shipper<input type="checkbox" value="3" data-original-title=""></label>
            </div>
        </div>


    var partyTypes = $("#update-checkbox").attr("data-type"); // gives  "Contractual Customer,Shipper
     $.each(partyTypes.split(','),
         function(i, opt) {
            //here i need to loop through all the label and checkbox inside div (id = update-checkbox) and  if the party type equals to the label then check that check box 

         });

例如,如果partytype = Contractual Customer,则选中相应的复选框

3 个答案:

答案 0 :(得分:2)

我认为不是循环​​遍历数组,而是可以迭代标签并查看它是否存在于数组中

var partyTypes = $("#update-checkbox").attr("data-type")||''; 
partyTypes = partyTypes.replace(/,\s+/g, ',');
var array = partyTypes.split(',');
$('#update-checkbox label.checkbox').filter(function () {
    return $.inArray($.trim($(this).text()), array) > -1
}).find('input').prop('checked', true)

演示:Fiddle

答案 1 :(得分:2)

var partyTypes = $("#update-checkbox").attr("data-type"); // gives  "Contractual Customer,Shipper
     $.each(partyTypes.split(','),
         function(i, opt) {

             $( ".checkbox" ).each(function( ) {
                 //console.log(opt);
                 if($( this ).text()==$.trim(opt)) {


                     $(this).find('input:checkbox').prop('checked',true);
                 }
          }) ;

         });   

空格的解决方案...... http://jsfiddle.net/jks8S/2/

答案 2 :(得分:0)

我首先在标签上设置“for”属性,然后您只需要进行一次检查。

或许没有......没有JS =好。

然后可能对标签进行设计,使其成为可点击的大区域。

相关问题