问题
I have lots of checkbox
element on my Grails form
, one is this:
<g:checkBox id="consolidate" name="consolidate" value="${true}" checked="${false}" />
Then on the receiving controller
, I verify the value of the checkbox
using this code
:
println params?.consolidate
And it displays:
on
Regardless whether I've tick my checkbox or not. In other language, if the checkbox is not ticked, its value on the controller will be null
or undefined
. What should be its value when unchecked, and what is the right code to access its value on the grails controller?
Temporary Solution:
The following code (on JavaScript
) is what I had used temporarily to accommodate my requirement. Though what I want is an explanation or maybe correction about this behavior.
var serialized_string = "";
$("#form input").each(function(i, j) {
var o = $(j);
if(o.val() !== undefined && o.val() !== "undefined" && o.val() !== "") {
if(serialized_string === "") {
serialized_string += o.attr("name") + "=";
}
else {
if(o.attr("name") === "consolidate") {
var val = "false";
if(o.prop("checked")) {
val = "true";
}
data += val;
}
else {
data += "&" + o.attr("name") + "=";
}
}
}
});
回答1:
If checked, you see the on you're seeing; otherwise you see null, which is your false.
来源:https://stackoverflow.com/questions/30364227/my-checkbox-pass-value-even-unchecked-grails