2

我需要使用 Play 框架获取未选中复选框的值。如果我选中复选框,我可以获得值。

我的html如下

   <input type="checkbox" name="correctAnswer" value="true">

这就是我在控制器中获取数据的方式,这给了我一个只有选中框的数组

  String[] segaMega = request().body().asFormUrlEncoded().get("correctAnswer");

我曾尝试在复选框技巧之前执行隐藏字段,但效果不佳。play有什么可以帮助我的吗?

4

1 回答 1

0

As per your comment, you really need to have both the checked values and the full list of values on server side. The best bet would have a hidden field in the form which will hold the values of your checkboxes concatenated by a separator. In this example, I'll use a pipe (|).

<script type="text/javascript">
    function beforeSubmitQuestion() {
        var hidden = document.getElementById("hidChxValues");
        hidden.value = "";
        var checkboxes = document.getElementsByName("correctAnswer");
        for(var i = 0; i < checkboxes.length; i++) {
            hidden.value += checkboxes[i].value + "|";
        }
        return false;
    };
</script>

<form id="yourForm" onsubmit="beforeSubmitQuestion(); ">
    <input type="hidden" id="hidChxValues" />

    <input type="checkbox" name="correctAnswer" value="true" /> Valid
    <br />
    <input type="checkbox" name="correctAnswer" value="false" /> Invalid
    <br />
    <input type="submit" />
</form>

I've made a test in jsfiddle: http://jsfiddle.net/tdDbg/ with the exception that I use a type="text" instead of type="hidden" in order to see the concatenated values and added return false; at the end of onsubmit to avoid form submission to the server (that will return in an error).

The server side code can be handled using Play or another technology, even plain Servlets.

于 2013-03-31T21:54:51.167 回答