I have a jsp:
<form:select path="operation" onchange="myFunc(${oper.id})">
<c:forEach items="${operList}" var="oper">
<form:option label = "${oper.name}" value="${oper.id}|${oper.name}"/>...
And I have a js function myFunc(id) { alert(id); }
Then I change select value I see alert: undefined.
Wat's wrong?
I have a jsp:
<form:select path="operation" onchange="myFunc(${oper.id})">
<c:forEach items="${operList}" var="oper">
<form:option label = "${oper.name}" value="${oper.id}|${oper.name}"/>...
And I have a js function myFunc(id) { alert(id); }
Then I change select value I see alert: undefined.
Wat's wrong?
1 Answer
Reset to default 5You cant get the value ${oper.id}
outside the <forEach>
loop , as it is a element in the list.
To get the selected value from the dropdown onchange()
event , add the id
attribute to the field and get it in the javascript
jsp :
<form:select id="mySelect" path="operation" onchange="myFunc()">
<c:forEach items="${operList}" var="oper">
<form:option label = "${oper.name}" value="${oper.id}|${oper.name}"/>...
jquery:
function myFunc() {
var selectedValue= $("#mySelect").val();
alert(selectedValue);
}
And if you prefer to do it without jquery , here is the javascript version ,
function myFunc() {
var selectBox = document.getElementById("mySelect");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
or simply,
<form:select id="mySelect" path="operation" onchange="myFunc(value)">
<c:forEach items="${operList}" var="oper">
<form:option label = "${oper.name}" value="${oper.id}|${oper.name}"/>...
And in javascript,
function myFunc($val) {
alert($val);
}
passed the value
attribute with the function call as the parameter.
hope this helps!!