Gideon
Gideon

Reputation: 1547

my checkbox pass value even unchecked - Grails

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") + "=";
            }
        }
    }
});

Upvotes: 1

Views: 1502

Answers (1)

mohsenmadi
mohsenmadi

Reputation: 2377

If checked, you see the on you're seeing; otherwise you see null, which is your false.

Upvotes: 1

Related Questions