I have the below code. How do I pass the selected value to another scriptlet? I tried doing "getAttribute", but it didn't work. So the below code lists car types and I select a value but don't know how to pass the selected value to a second dropdown list which further populates based on the selected value.
First dropdown:
<div class="cell">
Select Car_Type
<div class="input-control">
<select id="carid" name="carid">
<option selected disabled>--SELECT CAR TYPE--</option>
<%
ArrayList<Integer> carList = CarListDAO.getCar(id);
for (int c: carList){
out.println("<option value='" + c + "'>" + c + "</option>");
request.setAttribute("c", c);
}
%>
</select>
</div>
</div>
Pass selected value from above into function below:
<div class="cell">
Select Car_Engine
<div class="input-control">
<select id="carENGINE" name="carENGINE">
<option selected disabled>--SELECT CAR Engine--</option>
<%
ArrayList<String> carEngine = CarListDAO.getCarEngine(SELECTED_VALUE_FIRST_DROPDOWN); <----selected value from first dropdown passed to this method
for (String y: carEngine){
out.println("<option value='" + y + "'>" + y + "</option>");
request.setAttribute("y", y);
}
%>
</select>
</div>
</div>
You either need to implement some way to send the selected value back to the server to get the list of other options or you can embed you objects in JSON on your web page and use JavaScript on the client to change the options:
<%
Map<int, ArrayList<String>> engines = new Map<int, ArrayList<String>>();
ArrayList<Integer> carList = CarListDAO.getCar(id);
for (int c: carList){
ArrayList<String> carEngine = CarListDAO.getCarEngine(c);
engines.put(c, carEngine);
}
%>
<script>
var engines = <%out.println(JSONObject.valueToString(engines));%>;
function showEngines() {
var el= document.getElementById('carid');
for(var i=0;i<el.options.length;i++) {
if (el.options[i].selected) {
bindEngines(el.options[i].value);
break;
}
}
}
function bindEngines(c) {
var el=document.getElementById('carENGINE');
el.options.length = 0;
var newOptions= engines[c];
for (i=0; i<newOptions.length; i++)
{
el.options[el.length] = new Option(newOptions[i], newOptions[i]);
}
}
</script>
<div class="cell">
Select Car_Type
<div class="input-control">
<select id="carid" name="carid" change="showEngines()">
<option selected disabled>--SELECT CAR TYPE--</option>
<%
for (int c: carList){
out.println("<option value='" + c + "'>" + c + "</option>");
}
%>
</select>
</div>
</div>
<div class="cell">
Select Car_Engine
<div class="input-control">
<select id="carENGINE" name="carENGINE" disabled>
<option selected disabled>--SELECT CAR Engine--</option>
</select>
</div>
</div>