Patrick Patrick - 1 year ago 75
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.


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
on the input field, so that
on click
will make
<input class="ownplace" type="checkbox">
will be
<input class="ownplace" type="checkbox" checked="checked">

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


Answer Source

Use prop() function instead:

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


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 );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download