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>
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.
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
The Input Checkbox defaultChecked property in HTML is used to return the default value of checked attribute. It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.
If I understand the question, you want to change the value of the checkbox depending if it is checked or not.
Here is one solution:
$('#checkbox-value').text($('#checkbox1').val()); $("#checkbox1").on('change', function() { if ($(this).is(':checked')) { $(this).attr('value', 'true'); } else { $(this).attr('value', 'false'); } $('#checkbox-value').text($('#checkbox1').val()); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false"> <div id="checkbox-value"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With