我遇到的情况是,我需要更改复选框的值,无论是否已选中以进行错误验证。
设置就像这样
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>
我尝试过使用.attr('checked', 'checked')
和.prop('checked', true)
,但我所做的一切似乎都无效。
当我点击标签时,将选中复选框(显示复选标记),但是当我点击复选框时,我检查时DOM中的值会发生变化,但不会显示复选标记。
这里似乎有什么问题?
答案 0 :(得分:3)
我不确定你要做什么。但这将有效
但是,如果选中该复选框,您的服务器将仅检索术语的值,因此只测试它是否在服务器上设置
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>