简体   繁体   中英

Handle checked and unchecked checkbox

I have a very confusing situation here.

<tr>
    <td>
        <input type="checkbox" id="box1" name="box1" <% if (renderRequest.getPreferences().getValue("box1", null).equals("on")) { %> checked="checked"  <% } %> >
    </td>
    <td><label>Box</label></td>
</tr>

In the portlet.xml I have set the box1 value as "on" by default. So when I load the edit.jsp page I see the value as checked. Now, I want to handle the situation of unchecked checkbox which I am confused about. When I uncheck the box the value submitted is null and I am confused to handle the situation. How to submit a default value if the checkbox is unchecked.

Though this question was asked 3 years ago, I'm adding an answer for future viewers.

If a checkbox is unchecked, it doesn't get sent. So devang 's answer of setting it's value to "on/off" if it isn't checked isn't going to help - it will always return NULL.

The easiest solution I have found is to add a hidden field with the same name that will be used if the check-box is unchecked.

For eg, in your code, a solution could be

<tr>
    <td>
        <input type="checkbox" id="box1" name="box1" value="1" <% if (renderRequest.getPreferences().getValue("box1", null).equals("on")) { %> checked="checked"  <% } %> >
    </td>
    <td>
        <input type="checkbox" id="box1_hidden" name="box1" value="0" >
    </td>
</tr>

The above piece of code depends on the server handling of parameters as browser will send both the parameters. If the checkbox is unchecked, the hidden field's value gets used as-is (since browser does not sends the null parameter). However, things become cumbersome if the checkbox is checked, since now the browser sees two values corresponding to the same name field.

Java for example, offers only the first value of a field with a particular name. PHP, on the other hand, takes the last value as the one to use.

Thus, you need to perform one extra step and invoke JavaScript. The idea is to disable the hidden input based on the checked condition.

if(document.getElementById("box1").checked) {
     document.getElementById('box1_hidden').disabled = true;
}

This constitutes the complete solution irrespective of the server handling.

As far as I remember, adding value attribute and set it to the value you want should work. Below, value="on" is added.

<input type="checkbox" id="box1" name="box1" value="on" 
  <% if (renderRequest.getPreferences().getValue("box1", null).equals("on")) { %>    
    checked="checked"  
  <% } %> >

使用剃刀语法:

<input type="checkbox" name="xxx" value="xxx" @if(condition == true) {<text>checked="checked"</Text>}>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM