Checkbox selected in function

Asked

Viewed 25 times

0

I have a function and I’m trying to set the checkbox as true, in function, this way:

 $("#cbpre").checked = true;

But he’s not checking, I’ve debugged, and he enters this part, just doesn’t check the checkbox.

2 answers

3


.prop()

 
  $("#cbpre").prop('checked', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="cbpre"" type="checkbox">

OR

.attr()

 $("#cbpre").attr('checked','checked')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="cbpre"" type="checkbox">

What is the difference between . prop() and . attr()?

2

You can use the method attr or the method prop jquery to that:

$('#ck1').attr('checked', 'checked');
$('#ck2').prop('checked', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
   Checkbox 1: <input id='ck1' type="checkbox" />
</p>
<p>
   Checkbox 2: <input id='ck2' type="checkbox" />
</p>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.