Reputation: 1618
I've got a check box designed and styled like this:
<div class='checkbox'>
<label for="test">
<div class="switch">
<input type="checkbox" name='test' id='test' value="1"/>
<div class="slider"></div>
</div>
</label>
</div>
When the user clicks on the checkbox, I'm calling an external page and getting a return value. If the value <= 0 then I need to stop the checkbox being checked.
This the Jquery I'm using that doesn't work..
$("body").on('change', '#test', function(){
var check = $(this).attr('id')
if (document.getElementById(check).checked) {
$.ajax({ type: "GET",
url: "do.php?mode=check=" + check,
async: true,
success : function(text) {
console.log (text)
if (text === '0')
$('#test').attr('checked', false);
}
});
}
})
How can I update the styled checkbox so it is unchecked and shows as unchecked onscreen ?
Thanks
Upvotes: 1
Views: 3997
Reputation: 131
The $(element).attr()
function is deprecated as of jquery 1.6. You should use $("#test").prop("checked",false)
instead.
From the jquery documentation:
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
Upvotes: 1
Reputation: 8210
Use the disabled
attribute.
<input type="checkbox" name='test' id='test' value="1" disabled />
This disables the unchecked checkbox. You can remove it with JavaScript if you wish to have the user check it again. But in your case, i'd go with a manual jQuery check.
Disable by default, then have the ajax request go through as soon as the user clicks on it. After that, do something like:
if(callback =< 0) { $('#checkbox').prop('checked', true) }
More about disabled here
Upvotes: 0