2

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 1

5

You 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!!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.