Pearl
Pearl

Reputation: 414

How to get the selected value from drop down list in jsp?

<select name="item">
<c:forEach items="${combo}" var="id">
    <option value="${id}">${id}</option>
</c:forEach>
</select>

How can we get the selected value from the above dropdown list?

Upvotes: 14

Views: 207108

Answers (5)

y07k2
y07k2

Reputation: 2052

I've got one more additional option to get value by id:

var idElement = document.getElementById("idName");
var selectedValue = idElement.options[idElement.selectedIndex].value;

It's a simple JavaScript solution.

Upvotes: 1

user612
user612

Reputation: 29

    <%-- if you want to select value from drop-downlist here is jsp code. --%>
    <body>
    <form name="f1" method="get" action="#">
       <select name="clr">
           <option>Red</option>
           <option>Blue</option>   
           <option>Green</option>
           <option>Pink</option>
       </select>
     <input type="submit" name="submit" value="Select Color"/>
    </form>
    <%-- To display selected value from dropdown list. --%>
     <% 
                String s=request.getParameter("clr");
                if (s !=null)
                {
                    out.println("Selected Color is : "+s);
                }
      %>
</body>

Upvotes: 2

JohnRose
JohnRose

Reputation: 409

use jquery

$("#item").change(function({
    var x=$(this).val();
});

Your value will be in x variable, use this variable value in your jsp, like this {x} this statement will give the value

Upvotes: 3

Cԃաԃ
Cԃաԃ

Reputation: 1258

I know that this is an old question, but as I was googling it was the first link in a results. So here is the jsp solution:

<form action="some.jsp">
  <select name="item">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
  <input type="submit" value="Submit">
</form>

in some.jsp

request.getParameter("item");

this line will return the selected option (from the example it is: 1, 2 or 3)

Upvotes: 35

Milind Anantwar
Milind Anantwar

Reputation: 82241

Direct value should work just fine:

var sel = document.getElementsByName('item');
var sv = sel.value;
alert(sv);

The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.

Upvotes: 3

Related Questions