I am trying to create a simple way to force a single checkbox to display “No” in a form submission if left unchecked, or clicked off. I’ve tried a number of ways and this is the closest I can get, but it still isn’t working properly.
Any help is much appreciated.
Matt
$(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();
So to start out quite frankly, I’m not sure where you saw that sort of function setup before. You’re code, as-is, could be reduced to this:
The
valueof the checkbox, however, is never displayed on the screen. You may need to update a separate field with the values “Yes” or “No”, such as:And the script:
EDIT: Working jsFiddle
If you need to check whether the box is checked on the server-side post-form-submission, then you could also update a hidden input field with the value “Yes” or “No” and ignore the submitted checkbox element value (as
jaredhoytmentioned in his answer).