How to check "checkbox" dynamically - jQuery Mobile
With HTML a checkbox is created like this:
<form>
<input type="checkbox" id="category1">Category1<br>
</form>
With javascript we can check the checkbox like this:
$("#category1")[0].checked = true
Now I am trying to create the same page with jquery-mobile. The checkbox looks like this:
<form>
<label>
<input name="checkbox-0 " type="checkbox">Check me
</label>
</form>
Why is there is no id
here? Is the name the id
? Should I delete the attribute name and create one with the name id
?
How can I check this checkbox here with Javascript/jQuery?
I tried the code above, but it doesn't seem to work for this checkbox.
Solution 1:
You need to refresh it after changing its' .prop
, using .checkboxradio('refresh')
. This is the correct way to check checkbox/radio in jQuery Mobile.
Demo
$('.selector').prop('checked', true).checkboxradio('refresh');
Reference: jQuery Mobile API
Solution 2:
You can do:
$('input[name="checkbox-0"]').prop("checked", true).checkboxradio('refresh'); //sets the checkbox
var isChecked = $('input[name="checkbox-0"]').prop("checked"); //gets the status
Solution 3:
Straight from the jQ Mobile docs:
$("input[type='checkbox']").attr("checked",true);