1

I have a unique checkbox modal window

<div class="tv-choices" style="display:none;"><!-- turned on via button-->
<div class="choices-title">TV</div>
<div class="choices-checkboxes">
    <div class="category_box">
        <input type="checkbox" id="getf{038}" name="getfItem" value="Adult Animated">
        <label for="get{038}">Adult Animated</label>
    </div>

    <div class="category_box">
        <input type="checkbox" id="getf{9FA}" name="getfItem" value="Anime">
        <label for="get{9FA}">Anime</label>
    </div>

    <div class="category_box">
        <input type="checkbox" id="getf{821}" name="getfItem" value="Award Shows">
        <label for="get{821}">Award Shows</label>
    </div>
</div>

Now I have a multi-dimensional array:

object_with_arrays['genreAry'+ary_Num]

Let's say Array object_with_arrays[genreAry1] has: Adult Animated and Anime but not Award Shows. How would you now get those checkboxes to get checked via jQuery?

Project story: I have 9 generated buttons which create a Modal window on the fly, each modal window serves up a set of checkboxes. Since I'm using 1 modal window I have to clear out the pervious checkboxes. I found this code below which works, but I just can't seem to figure out how to re-populate the checkboxes with my Arrays

$('.tv-choices').find(':checked').each(function() {
        $(this).removeAttr('checked');
    });
4

2 回答 2

2
$('.modal').find('input[type="checkbox"]').each(function() {
   var state = $.inArray(this.value, object_with_arrays['genreAry1'])!=-1;

   $(this).prop('checked', state);
});

遍历复选框,并根据数组中是否存在复选框值来设置选中的属性?

于 2013-05-03T21:21:33.520 回答
2

您可以使用 jQuery 过滤属性。如果您只寻找一个项目,它会是这样的:

$('.modal').find('input:checkbox[value="Anime"]').each(function() {
   $(this).prop('checked', true);
});

但由于您想检查值列表,您可以使用filter回调:

var searchValues = object_with_arrays['genreAry'+ary_Num]; 
//e.g. searchValues == ["Anime", "Adult Animated"]

$('.modal').find('input:checkbox').filter(function() {
   return searchValues.indexOf($(this).val()) >= 0;
}).each(function() {
   $(this).prop('checked', true);
});

如果您还想取消选中所有其他复选框:

$('.modal').find('input:checkbox').each(function() {
   var checked = searchValues.indexOf($(this).val()) >= 0;
   $(this).prop('checked', checked)
});
于 2013-05-03T21:23:16.623 回答