checkbox selected using jquery and id

时间:2016-11-09 08:18:18

标签: jquery css3

I am trying to select the ckeckbox using jquery and adding the class.

Checkbox Code :

<label>
  <span class="custom-checkbox">
    <input type="checkbox" name="is_global" id="check">
  </span>
</label>

In my code. if i want to select checkbox than add class selected in span tag. like this :

<label>
  <span class="custom-checkbox selected">
    <input type="checkbox" name="is_global" id="check">
  </span>
</label>

So my questiona is how to add class selected using jquery with id check.

i have tried following. but not working.

$("#check span['custom-checkbox']").addClass('selected');

5 个答案:

答案 0 :(得分:1)

Select element using id and get it's parent using parent() method.

$('#check').parent().addClass('selected')


Or use :has() selector to get element which cotains any particular elemnt.

$('.custom-checkbox:has(#check)').addClass('selected')

答案 1 :(得分:1)

$("#check").parent().addClass('selected');

or

$("#check").parents('.custom-checkbox').addClass('selected');

https://api.jquery.com/parent/

https://api.jquery.com/parents/

try something like this

$('#check').change(function() {
    $(this).parents('.custom-checkbox').toggleClass('selected', $(this).is(':checked'));
})

答案 2 :(得分:0)

Replace this :

$("#check span['custom-checkbox']").addClass('selected');

By this :

$('#check').change(function() {
    $check = $(this);
    if ($check.is(':checked')) {
        $("span.custom-checkbox").addClass('selected');
    }
}

Because .custom-checkbox is a class and you want to test if the input is checked before adding the class.

Source : https://jsfiddle.net/gabrieleromanato/dHZS9/

答案 3 :(得分:0)

try this

$("#check").parent().addClass('selected');

答案 4 :(得分:0)

document.getElementById("check").checked = true;

只要您希望检查它,请尝试使用此代替最后一个语句。