0

I have a JSP with a select input in a form, like so:

<form method="post" action="/confirm">
  <select id="dropdown" name="dropdown">
    <option value="1">1st choice</option>
    <option value="2">2nd choice</option>
    <option value="3">3rd choice</option>
  </select>
  <input type="submit" value="submit" name="submit" />
</form>

I have a spring controller that handles this form as follows:

@RequestMapping(value = "/confirm", method = RequestMethod.POST)
public ModelAndView confirm(@RequestParam int dropdown,
                            HttpServletRequest request,
                            Model model)
{
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("selection", dropdown);
    modelAndView.setViewName("confirm");
    return modelAndView;
}

On my confirm view, if I want to display the value of the dropdown selection then I can do that like this:

<div id="dropselection">${selection}</div>

If the user selected the first option, "1st choice", for example, then the value that would be passed to the confirm page would be 1.

However, what if I want to pass along the text value from the select tag option? What if a user selected the first option and I needed the value 1st choice to be passed into the controller? How would I retrieve that?

1

1 Answer 1

1

You can't retrieve that value. In form submission it only pass value attribute of select, input tags.

Two options available

  1. You can change value field text to description

If you have hard code that just change that to

<option value="3rd choice">3rd choice</option>

If you have dynamic code, then you can use this kind of approach

List<Answer> answerList = new ArrayList<Answer>();
Answer answer = new Answer();
answer.setAnswerId(3);
answer.setDescription(3rd choice);
ModelAndView modelAndView = new ModelAndView();     
modelAndView.addObject("answerList", answerList);   

<select id="dropdown" name="dropdown">
    <option value="">Select</option>
    <c:forEach items="${answerList}" var="answer" varStatus="answerStatus">
        <option value="${answer.description}" label="${answer.description}"/>
    </c:forEach>
</select>

or keep options as it is and in controller level you can get that value from dropdown request parameter (example: 3)

And after that you can loop the answer list (answerList) and find value in controller level.

<c:forEach items="${answerList}" var="answer" varStatus="answerStatus">
    <option value="${answer.answerId}" label="${answer.description}"/>
</c:forEach>

Note

answer.answerId = 3
answer.description = 3rd choice
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.