我试图创建一种简单的方法来强制单个复选框在表单提交中显示“否”(如果未选中或单击不显示)。我已经尝试了多种方法,这是我可以获得的最接近的方法,但是仍然无法正常工作。任何帮助深表感谢。马特$(function opt() { if ($("#optIn").is(":checked")) { $("#optIn").value="Yes" $("#optIn").click(function() { this.value="No" }) } else { $("#optIn").value="No" $("#optIn").click(function() { this.value="Yes" }) } return false});opt(); 最佳答案 因此,坦率地说,我不确定您以前在哪里看到过这种功能设置。您的代码按原样可以简化为:$(function() { // on DOM ready (when the DOM is finished loading) $('#optIn').click(function() { // when the checkbox is clicked var checked = $('#optIn').is(':checked'); // check the state $('#optIn').val(checked ? "Yes" : "No"); // set the value }); $('#optIn').triggerHandler("click"); // initialize the value});但是,复选框的value永远不会显示在屏幕上。您可能需要使用“是”或“否”值更新一个单独的字段,例如:<input type="checkbox" id="optIn" /><span id="optInLabel"/>No</span>和脚本:$(function() { // on DOM ready (when the DOM is finished loading) $('#optIn').click(function() { optIn(this); }); optIn($('#optIn')[0]);});function optIn(el) { var checked = $(el).is(':checked'); // check the state $('#optInLabel').html(checked ? "Yes" : "No"); // set the value}编辑:Working jsFiddle如果您需要检查服务器端提交表单后是否选中了该框,则还可以使用值“是”或“否”更新隐藏的输入字段,并忽略提交的复选框元素值(如在他的答案中提到)。
09-26 04:46