5/26/2011

Doing a Post with unchecked checkboxes

If you have to do JSPs you will certainly run into the problem that you have to submit a Form where you can enable or diasble certain form elements. That´s ok for checkboxes, because if they are not checked, they are won´t get submitted. But what about input fields ? They will be submitted all the time, regardless of the checkbox. This will lead to difficulties processing the fields values in the portlet class, because you will have (for example) 2 values for the selected checkbixes and 6 values for all input fields.


The solution is to dynamically disable all input fields that should not be submitted.


You can do it by javascript like this:

function toggleDisable(identifier) {
  document.getElementById(identifier).disabled = 
(document.getElementById(identifier).disabled) ? false : true;
}

This function toggles the desired input field from disabled to enabled and back. And this is the checkbox doing the javascript call:


<input type="checkbox"onclick="toggleDisable('fieldId');" name="CBName" value="CBName" <%=selected %>>

The Input Field itself is very straightforward:


<input id="fieldId" name="field" <%=disabled %>  type="text" value="value" />


By doing this you can make sure, that you will always submit as much checkbox values as input field values.


If you like this tutorial it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)

If you have any questions, feel free to leave a comment.