hackfield hackfield - 2 years ago 115
Javascript Question

Hide/Show child items on a dropdown onchange of the other dropdown value (parent)

I have simple filtering to be done possibly using javascript. I am new to javascript. I have a vehicle makeList and vehicle modelList coming from the java to my JSP.

<tr><td><form:label path="makeId">Make: </form:label></td>
<td><form:select path="makeId" required="true">
<form:options items="${makeList}" itemValue="makeId" itemLabel="makeName"></form:options>
<td><form:label path="modelId">Model: </form:label></td>
<td><form:select path="modelId" required="true">
<form:options items="${modelList}" itemValue="modelId" itemLabel="modelName"></form:options>

All I want to do is onchange of make , show only those model associated with that make and hide rest

Hope someone can get me a simplest solution

Answer Source


Following changes gave me the solution:

  1. Iterating the modelList and assigning the makeId to id

            <td><form:label  path="modelId">Model: </form:label></td>
            <td><form:select  path="modelId" required="true">
                     <c:forEach items="${modelList}" var="model">
                        <form:option value="${model.modelId}" id="${model.makeId}" ><c:out value="${model.modelName}"/></form:option>

  1. jquery onchange of Make dropdown:

$("#makeId").show( function() { var makeId = $(this).attr('value'); $("#modelId option[id !=" + makeId + "]").hide().attr("selected", false); $("#modelId option[id ="+makeId+"]").show().attr("selected",true); });

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download