I have a form with checkbox and I want to keep it checked after submitting the form when it goes back to the same view with an error. I heard that the value attribute can help me to make the checkbox be checked so im trying to set it to true/false. Anyway, the input value stays "false" even if I click it. What happens exactly? I thought the value goes true/false after clicking the checkbox
<input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false">
<script>
$("#checkbox1").is(':checked', function(){
$("#checkbox1").attr('value', 'true');
});
</script>
This question is related to
javascript
jquery
checkbox
Checkboxes can be really weird in JS. You're best off checking for the presence of the checked
attribute. (I've had older jQuery versions return true even if checked
is set to 'false'.) Once you've determined that something is checked then you can get the value from the value
attribute.
Try this
$("#checkbox1").is(':checked', function(){_x000D_
$("#checkbox1").prop('checked', true);_x000D_
});_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false">
_x000D_
I'm going to post this answer under the following assumptions.
1) You (un)selected the checkbox on the first page and submitted the form.
2) Your building the second form and you setting the value="" true/false depending on if the previous one was checked.
3) You want the checkbox to reflect if it was checked or not before.
If this is the case then you can do something like:
var $checkbox1 = $('#checkbox1');
$checkbox1.prop('checked', $checkbox1.val() === 'true');
jQuery.is()
function does not have a signature for .is('selector', function)
.
I guess you want to do something like this:
if($("#checkbox1").is(':checked')){
$("#checkbox1").attr('value', 'true');
}
To return true or false depending on whether a checkbox is checked or not, I use this in JQuery
let checkState = $("#checkboxId").is(":checked") ? "true" : "false";
Use Checked = true
$("#checkbox1").prop('checked', true);
Note: I am not clear whether you want to onclick/onchange event on checkbox. is(":checked", function(){})
is a wrong in the question.
Source: Stackoverflow.com