Question

I have a sumbit button gets his value from an expression language in foreach jstl as showin below ,I want when click three buttons get their values to the three hidden input respectively,but when run this code returns the first value in expression language

 <script>
 function myfunction()
 {
if(document.getElementById('demo1').value=""){
document.getElementById('demo1').value=document.getElementById('btn').value;
}else if(document.getElementById('demo2').value=""){
    document.getElementById('demo2').value=document.getElementById('btn').value;
}else
     {
    document.getElementById('demo3').value=document.getElementById('btn').value;
     }
}
   </script>
  <html>  
  <form:form action="Search" method="post">
  <input type="hidden" name="answer1" id="demo1">
  <input type="hidden" name="answer2" id="demo2">
  <input type="hidden" name="answer3" id="demo3">
  <c:forEach var="item" items="${group.subGroups}">
  <input id="btn" type="submit" 
  value="${item.subGroupName}" onclick="myfunction()">  
  </c:forEach> 
  <form:form>
  </html>
Was it helpful?

Solution

First of all, testing for equality is made using ==not = which is used for assigning values. So

if(document.getElementById('demo1').value=""){
   [...]
}

becomes

if (document.getElementById('demo1').value == "") {
   [...]
}

And then, if you have multiples buttons output by your JSTL forEach (the <input id="btn"...> ones), you must provide multiple ids or use another way of referring to them; otherwise, how can the browser know which button you are trying to access ?

The other way would be something like :

 function myfunction(element)
 {
     if (document.getElementById('demo1').value == ""){
         document.getElementById('demo1').value = element.value;
     } else if (document.getElementById('demo2').value == ""){
         document.getElementById('demo2').value = element.value;
     } else {
         document.getElementById('demo3').value = element.value;
     }
 }

[...]

<input type="submit" value="${item.subGroupName}" onclick="myfunction(this)">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top