How do I bind a checkbox to a boolean in Play! fra

2019-04-04 15:43发布

An app I'm working on using the Play! Framework has an object called gift with a boolean property, called Taken. How do I show the state of this value as a checkbox on my view? I've tried :-

<input id="gift_Taken" class="" type="checkbox" name="gift.Taken" value="true"  />
<input type="hidden" name="gift.Taken" value="false" />

based on examples I've seen from the autogenerated CRUD forms, but the checkbox is not checked when the property is True, which is what I'm aiming for.

Anyone know the correct way to achieve this?

3条回答
啃猪蹄的小仙女
2楼-- · 2019-04-04 16:19

You just need to set the checked value against the checkbox, if the value is true.

for example (assuming the object sent in from the view is called gift, and the boolean value is called Taken.

<input id="gift_Taken" type="checkbox" name="gift.Taken" ${gift.Taken ? 'checked':''}  />
查看更多
一纸荒年 Trace。
3楼-- · 2019-04-04 16:24

The accepted answer is actually not 100% correct as it doesn't handle the "unchecked" case. To handle both cases you need a hidden field:

<input id="gift_Taken" type="checkbox" name="gift.Taken" ${gift.Taken ? 'checked':''}  />
<input type="hidden" name="gift.Taken" value="false" />

Note that the placement seems to be important, so the hidden field must be after the checkbox.

Writing a custom template tag for this, makes it easy not to forget the hidden input (put this into views/tags/checkbox.html):

<input id="${_id}" type="checkbox" name="${_name}" value="true" #{if _checked} checked="checked" #{/if}>
<input type="hidden" name="${_name}" value="false">

Then call this template like this:

#{checkbox id:'gift_Taken', name: 'gift.Taken', checked: gift.Taken /}

See also the related discussion on the play framework list: https://groups.google.com/forum/?fromgroups=#!topic/play-framework/HygQuYF3a8E

查看更多
我想做一个坏孩纸
4楼-- · 2019-04-04 16:38

If you are able to use javascript, you can use:

$(document).ready(function() {
    $( ":checkbox" ).each(function() {
        var name = $(this).attr("name");
        if(typeof(name) != "undefined") {
            var checkboxString = "";
            checkboxString = '<input type="hidden" style="display:none;" name="'+ name +'" value="false" />'
            $(this).after(checkboxString);
        }
    });
});
查看更多
登录 后发表回答