Skip to content
Advertisement

Trying to get value out of a select option in the same form

I’m trying to get value out of the select option. But it doesn’t seems to be able to get since it’s on form. How do I do it ? I mean by having taking the value out of the option select.

<strong>Select a product :</strong>
    <select name="stockid">
     <c:forEach var="row" items="${STOCKS1.rowsByIndex}">
      <option selected><c:out value="${row[0]}"/></option>
     </c:forEach>
    </select>
    </p>
<%!int query = 0; %>
 <%   
        if(request.getParameter("stockid") != null){
            Connection connection = DriverManager.getConnection(
                "jdbc:derby://localhost:1527/healthdb", "nbuser", "nbuser");

            PreparedStatement statement = connection.prepareStatement("select stockqty from stocks where stockid = ?");


            statement.setString(1,request.getParameter("stockid"));
            ResultSet resultset = 
                statement.executeQuery( ) ; 
        if(resultset.next()){
            out.print(resultset.getString("stockqty"));
            query = resultset.getInt("stockqty");
        }
 else
 out.print("lol");}%> 

Advertisement

Answer

1.) You can not select all the items in a select with selected ! Without multiple="multiple"

 <c:forEach var="row" items="${STOCKS1.rowsByIndex}">
  <option selected><c:out value="${row[0]}"/></option>
 </c:forEach>

E.g. topFr[]

<select name = "topFr[]" multiple="multiple">
    <option selected="selected">Apple</option>
    <option>Pear</option>
    <option selected="selected">Peach</option>
</select>

if you can have multiple selected the name must be an array here stockid[]

<select name="stockid[]">

If you get from the <Form> an array you must treat request.getParameter("stockid")as an array !

2.) OR stockid = INT then

You can not pass a string to a field = INT

if stockid is INT !

statement.setString(1,request.getParameter("stockid"));

will set a String to the query and the String will be quoted

wrong

select stockqty from stocks where stockid = "1" 

you need

select stockqty from stocks where stockid = 1 

Try

statement.setInt(1,Integer.parseInt(request.getParameter("stockid"));

also you should test with for empty !

String res = request.getParameter("stockid");
if(res != null && !res.isEmpty()){
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement