jQuery:根据单独的label元素添加属性

时间:2014-04-02 11:59:01

标签: javascript jquery

我正在尝试根据复选框标签文本将复选框列表动态标记为“已选中”。

以下是一些标记示例:

    <li class="checkboxlist-item">
    <input type="checkbox" id="Categories_24" value="eb9d6610-914b-4e14-99d1-a22200cd5369" name="Categories.SelectedIds"  />
    <label for="Categories_24">Properties &amp; Moving</label>
</li>

所以如果标签文字是“Properties&amp; Moving”,我想在这里将输入元素标记为“已选中”

非常感谢您的帮助 - 谢谢!

7 个答案:

答案 0 :(得分:2)

我会使用.filter,因此您可以确定完全字符串:

$(".checkboxlist-item label").filter(function() {
    return $(this).text() === "Properties & Moving";
}).siblings(":checkbox").prop("checked", true);

Example jsFiddle

答案 1 :(得分:1)

试试这个:

$('label:contains(Properties & Moving)').siblings(':checkbox').prop('checked', true);

Updated Fiddle

答案 2 :(得分:0)

您可以使用.each()方法遍历每个复选框。然后使用.next(),您可以找到旁边的标签元素。

$("input[type=checkbox]").each(function(){
if($(this).next().text()=="Properties & Moving")
{
    $(this).prop("checked",true);
}
});

Fiddle

答案 3 :(得分:0)

if( $('.checkboxlist-item label').text() == 'Properties Moving' )
 $('.checkboxlist-item input').prop('checked', true);

答案 4 :(得分:0)

首先通过查找标签文本 if($(“label”)。text()==“Properties&amp; Moving”) 然后添加选中的代码 喜欢checked =“checked”

答案 5 :(得分:0)

$("input:checkbox").each(function(){
if($('label[for=' + this.id + ']').html()=="Properties &amp; Moving")
{
    $(this).prop("checked", true);
}
});

演示:

http://jsfiddle.net/BC2Q6/

答案 6 :(得分:0)

$('label').each(function(){
    if($(this).html()=='Properties &amp; Moving'){
        $(this).siblings(':checkbox').prop('checked', true);
    }
});

Demo Fiddle