Here I am displaying 24 checkboxes.I want to get all the values of checked checkboxes in action class and insert it as a new record inside database.Inserting will be done on
The value
attribute should not be empty value=""
. If you followed the linked answer you have seen that s:checkbox
tag is used. When this tag is rendered it provided the field value for both checked and unchecked checkbox. And remarking Dave Newton's notice in his book "It should have values true
or false
the only viable values for the moment. These are only values that work correctly with checkbox
interceptor."
The tag renders a single checkbox . At the time of this writing it only works well with Boolean (or boolean) properties. Attempting to preselect a checkbox with, for example, a string value only works if the string is true or false .
There's an example Struts 2 checkbox example, which is using such fieldValue
attribute.
If you want a deep incite into how checkbox
interceptor is working you can read <s:checkbox> not auto populating in struts2 form.
Another example that is using multiple checkboxes Struts 2 multiple check boxes example. Unlike the s:checkbox
it doesn't work with any unchecked values and you can map values directly using listKey
and listValue
attributes.
I just changed my datatype of variable from boolean to string[] . It will store the values of the checkbox selected. Below is my jsp.
<s:form action="resultAction" namespace="/">
<h2>
<input name="checkMe" type="checkbox"
class="formcheckbox" value="Rangabhoomi"><span
class="formcheckbox_content">Rangabhoomi</span>
<input
name="checkMe" type="checkbox" class="formcheckbox"
value="Fire Noc"><span class="formcheckbox_content">Fire NOC</span>
</h2>
<input type="submit" value="Submit" />
</s:form>
Below is my action class
package com.checkboxInStruts2;
import com.opensymphony.xwork2.ActionSupport;
public class CheckboxAction extends ActionSupport
{
private String checkMe[];
public CheckboxAction() {
// TODO Auto-generated constructor stub
}
public String[] getCheckMe() {
return checkMe;
}
public void setCheckMe(String[] checkMe) {
this.checkMe = checkMe;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
for(int i=0;i<checkMe.length;i++)
{
System.out.println(checkMe[i]);
}
return "success";
}
}
and for display use below tag on jsp.It will display the array of string values of selected checkboxes.
<s:property value="checkMe"/>