Noir Antares Noir Antares - 4 months ago 32
Javascript Question

Dynamically changing text field value using JSTL

I'm a beginner at JSTL as I've only started using it recently to avoid using scriplets in my JSP, and I wanted to ask for help about something I've been stuck in.

I have a select element which I've managed to populate with an arraylist using JSTL. However I also need to dynamically change the value of a readonly text field whenever a different option in the dropdown list is selected, and the value to put in the text field is at the same index in the arraylist as the selected option, and that's where I'm having trouble with.

<select id="department" onchange="managerfill()">
<c:forEach var="dept" items="${departments}">
<option value="${dept.deptname}"><c:out value="${dept.deptname}"/></option>
</c:forEach>
</select>

<input type="text" id="manager" readonly>


I tried to use a js function to change the text field's value but so far, I've had no luck with getting it to work.

function managerfill() {
var x = document.getElementById("department").selectedIndex;
document.getElementById("manager").value="${departments[x].manager}";
}


It would have been easier if both department and manager fields were both dropdown lists, but we were required to make manager a text field so I'm kind of at a loss trying to work around it.

Answer

You can't use jstl language on rendered pages. jstl is server side only and can't be used on end-user browser.

You need to use js to change it.

The function you have wrote is good expect the jstl syntax that cannot be no more interpreted.

function managerfill() {
  var select = document.getElementById("department");
  var x = select.selectedIndex;
  document.getElementById("manager").value = select.options[x].text;
}

Something like this should work.

But I think that the text you want to print is server side, so you can print it in some html/tag or hidden select and take the result from it. replacing the select.options[x].text:

<select id="departments-manager" class="hidden">
  <c:forEach var="dept" items="${departments}">
    <option value="${dept.manager}"><c:out value="${dept.manager}"/></option>
  </c:forEach>
</select>


function managerfill() {
  var select = document.getElementById("department");
  var selectManager = document.getElementById("departments-manager");
  var x = select.selectedIndex;
  document.getElementById("manager").value = selectManager.options[x].text;
}
Comments