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

前端 未结 5 1569
难免孤独
难免孤独 2020-12-31 08:25

                        
    
提交评论

  • 2020-12-31 08:45

    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.

    0 讨论(0)
  • 2020-12-31 08:45
        <%-- 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>
    
    0 讨论(0)
  • 2020-12-31 08:55

    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

    0 讨论(0)
  • 2020-12-31 08:56

    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.

    0 讨论(0)
  • 提交回复
    热议问题