Patrick Patrick - 2 months ago 12
jQuery Question

.on(click) with attribute setting not working

I am trying to set an attribute of "checked" on a checkbox.

The code:

$(".ui.toggle" ).on( "click", function() {

if ($('#ownplace').not(':checked')) {
$('#ownplace').attr('checked', true );
}
else {
$('#ownplace').prop('checked', false);
}

});


It checkes the box alright, but then it wont uncheck. I have tried multiple solutions including using the attr instead of prop - and yes I have conducted a search, but nothing seems to clarify this particular problem.

EDIT

I need to be able to capture if the checkbox is checked, like so:

if($data['ownplace'] == checked) {
$user->ownplace = $data['ownplace'];
}


This workes:
$('#ownplace').prop('checked', !$('#ownplace').is(':checked'));
but it doesn't set the checked attribute on the field, so i cant check if its checked or not.

None of the solutions are setting
checked="checked"
on the input field, so that
on click
will make
<input class="ownplace" type="checkbox">
will be
<input class="ownplace" type="checkbox" checked="checked">
.

The
.prop
doesn't do that, and only toggles css I guess.

Patrick

Answer

Use prop() function instead:

$('#ownplace').prop('checked', true );

EXPLANATION

Using attr() will work too (but your if clause is wrong), but, prop() is most recommended.

If you want to check for the checkboxe's state use is(:checked)

if (!$('#ownplace').is(':checked')) {
   $('#ownplace').prop('checked', true );
}