1

There is a checkbox in my jsp page

<input type="checkbox" name="myCheck" id="myCheck">

I am submitting the form and on server side,I am trying to retrieve it using

request.getParameter("myCheck");

If I have checked the checkbox,it is coming in request as true else it is not present in request object.

My Requirement is that It should also come as false if I have not checked it. Any suggestion?

UPDATE

I am using GET method and yes it is present in the form which I am submitting.

RockAndRoll
  • 2,247
  • 2
  • 16
  • 35

2 Answers2

2

From accepted answer in stackoverflow

How you can know if its checked

Clarification..

For example:

<input type="hidden" name="checkboxNamesList" value="nameCheckbox1" />
<input type="hidden" name="checkboxNamesList" value="nameCheckbox2" />
<input type="hidden" name="checkboxNamesList" value="nameCheckbox3" />
<input type="hidden" name="checkboxNamesList" value="nameCheckbox4" />

Then, you can get checkboxNamesList from the request (it will be a String[]) so you will have all the checkboxes params names. If you get a parameter for one of the checkboxes name and value is null, it means that checkboxe was not checked

Well, as unchecked checkboxes are not present in the request you don't know whose checkboxes in the JSP were not checked but you need to know it in order to write in your data file something like checkbox_name1=unchecked.

So, how to do that? First, you need to know what checkboxes (uncheck or not) were present in the request. For that, you can use the code below and get name of all checkboxes present in the JSP:

String[] checkboxNamesList= request.getParameterValues("checkboxNamesList");

Then, let look for unchecked checboxes:

for (int i = 0; i < checkboxNamesList.length; i++) {

    String myCheckBoxValue = request.getParameterValues(checkboxNamesList[i]);

    // if null, it means checkbox is not in request, so unchecked 
    if (myCheckBoxValue == null)
        writer.append(checkboxNamesList[i] + "=unchecked");

    // if is there, it means checkbox checked
    else
        writer.append(checkboxNamesList[i] + "=checked");

}
Community
  • 1
  • 1
shareef
  • 9,255
  • 13
  • 58
  • 89
1

I cannot understand why the value is not in the request object. I think one possible mistake is the missing value attribute.

To your second question: In your backend you have to define a default value first and then check to null:

public boolean myCheckBox = false;
if (request.getParameter("myCheck") != null) {myCheckBox = true}
Reporter
  • 3,897
  • 5
  • 33
  • 47