Accessing a form variable inside javascript

2019-08-25 01:58发布

I have a code like this

<html>
<head>Title
<script>
function callme()
{ 
        alert("Hi");
              document.test.action ="testAction.do";
        alert(document.getElementById("option").value);     
        alert('<%=request.getParameter("option")%>'); 
}
</script>           }
</head>
<body>
<FORM method="post" name="test" >
<select name="option" id="option">
<option>1</option>
<option>2</option>
</select>
<input type="submit" value="Submit" onClick="callme()">
</form>
</body>
</html>

This is a sample jsp code of what I have to do.The problem is I am able to get value for the document.getElementById but I want to access this parameter inside my action class which is retunring as null.Can anyone help me in solving this issue.

2条回答
Evening l夕情丶
2楼-- · 2019-08-25 02:27

You need to set the onsubmit event on the form, else when someone hits enter, the function won't be called. Then inside the function the this keyword refers to the form element.

To use document.getElementById() you need to set id="myId" on the element you want to access.

What do you mean by you're action class is returning as null?

查看更多
倾城 Initia
3楼-- · 2019-08-25 02:46

Sounds a bit unclear. I presume what you are saying is that this line:

alert('<%=request.getParameter("option")%>');

shows null in the alert?

I think the main reason is that the form hasn't been submitted yet. You are using a server side "request" object, but you render this page nothing has been submitted yet hence request.getParameter("option") returns null.

If you submit this form then inside testAction.do (since this is where it will be submitted to) you will be able to read the value from request.getParameter("option")

查看更多
登录 后发表回答