below is my code (1.jsp)
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
document.write("\n value is"+selectedValue);
}
</script>
</head>
<body>
<form method="post" action="SampServlet">
<select id="selectBox" name="selurl" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</form>
</body>
</html>
Here I have inserted this code into a jsp page.And getting the value of "selectedValue" from javascript to scriptlet with in the same jsp like this.
<% String val=(String)request.getParameter("selurl");
System.out.println("\n selected value is:"+val); %>
I am getting selected value as null as output. And if I print javascript selectedValue parameter it is giving me correct output i.e.,output as the option selected.But in scriptlet am getting null.Where is the error.I included all headers and directives.Please help me.
Your select element should have a name attribute and you must use that name in request.getParameter()
EDIT:
If you want the server request to be made on the select element's onchange event, you must Ajax.
Using jQuery,
In your web browser you have only html, javascript and css. All JSP code is meant to be run on the server. So you get only the output of the jsp file. And after this you cannot change the jsp code.
Use submit Button to get Your Selected value at same page and no need any function,no need onsubmit.
for example:
You're missing the
<submit>
button.Add the button and click on it to submit the form to your servlet with the selected value sent as
selurl
. Please, note that your form'saction
attribute is pointing toSampServlet
which seems to be a servlet. For jsps we usually have something likeaction="page.jsp"
in the form.EDIT:
If you want to post the form automatically when the user selects a value from the drop-down just set your
onchange
to: (you won't even need the<submit>
button then)