How to submit the contents of form without losing its Value ?




Asked on July 03, 2016
I don't want to lose the elements in the form which is already selected. What I am trying to achieve is that, the user will select a option from the select element and press the submit button, based on the selected value a jstl code for database will run and show two more elements. How should I achieve this without using any framework and please I am new to this and I would like to explained in detail. Thank you!!



Replied on July 04, 2016
Suppose we have a bean.
class MyBean {
  private int id;
  private String name;
  //setter getter
}
Populate the above bean that need to be shown in select box.
You need to save the selected id of your selected value from select box in any scope, it can be request or session scope or return this id to the jsp in the next response.

So finally on we have two things.
1. List of MyBean 
 
List<MyBean> list = new ArrayList<>();
//add the values in the list

2. Selected id as selectedId

As you are using JSTL, show you can populate your select box as follows.

<select name="user">
    <c:forEach items="${list}" var="myBean">
        <option value="${myBean.id}" ${myBean.id == selectedId? 'selected' : ''}> ${myBean.name} </option>
    </c:forEach>
</select>

When selectedId will match with myBean.id, <option> tag will be assigned with an attribute selected and so the name associated with this id will be shown as selected in selected box.




Write Answer










©2024 concretepage.com | Privacy Policy | Contact Us