Reputation: 11670
I have a situation where I need to change the value of the checkbox whether it's checked or not for error validation purposes.
The setup is like this
jQuery(document).ready(function($) {
"use strict";
function toggle_checkbox_value(e) {
var $this = $(e.currentTarget);
e.preventDefault();
if (!$this.data('lockedAt') || +new Date() - $this.data('lockedAt') > 300) {
var $input_terms = $('#terms');
if ($input_terms.val() == '0') {
$input_terms.val('1');
$input_terms[0].checked = true;
} else {
$input_terms.val('0');
$input_terms[0].checked = false;
}
}
$this.data('lockedAt', +new Date());
}
$(document).on('click', 'label[for="terms"]', toggle_checkbox_value)
.on('click', '#terms', toggle_checkbox_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="terms" type="checkbox" name="terms" value="0">
<label for="terms" class="checkbox">I've read and accept the terms & conditions</label>
I've tried with .attr('checked', 'checked')
and with .prop('checked', true)
but nothing I did seems to work.
When I click on label, the checkbox will be checked (check mark shown), but when I click on the checkbox, the value changes in DOM when I inspect it, but the check mark is not shown.
What seems to be the issue here?
Upvotes: 0
Views: 53
Reputation: 178011
I am not sure what you are trying to do. But this will work
However your server will only retrieve the terms' value if the checkbox is checked so just test if it is set on the server
jQuery(document).ready(function($) {
"use strict";
$("#terms").on('click',function() {
this.value=this.checked?1:0;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="terms" type="checkbox" name="terms" value="0">
<label for="terms" class="checkbox">I've read and accept the terms & conditions</label>
Upvotes: 3