Issue
I'd like to know if it is possible to pass variables as a parameter from JSP to Onchange
function. If so, how to do it ?
<%>for(int i = 0; i < i < 100; i ++){<%>
<select name="<%= i %>user" id="<%= i %>" onchange="myFunction(<%=i%>)">
<option value="present">present</option>
<option value="absent">absent</option>
<option value="holiday">holiday</option>
</select>
<%>}<%>
function myFunction(i) {
var element = document.getElementById(i);
element.setAttribute("style", "background-color: red;");
}
I've been trying different ways, but it doesn't work.
Please help!
Solution
You can use <c:forEach></<c:forEach>
loop to iterate and use ${loop.index}
to get particular value i.e : 0,1..100
Your jsp code will look like below :
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
//begin from 0 loop till 100
<c:forEach begin="0" end="100" varStatus="loop">
<select name="${loop.index}user" id="${loop.index}" onchange="myFunction(${loop.index})">
<option value="present">present</option>
<option value="absent">absent</option>
<option value="holiday">holiday</option>
</select>
</c:forEach>
Your javascript code :
function myFunction(i) {
var element = document.getElementById(i);//getting id
element.style.background = "blue";//apply bg color
}
Answered By - Swati
Answer Checked By - Marie Seifert (JavaFixing Admin)