Dependent Select List With jQuery
A few days back I have implemented a simple dependable dropdown list with jQuery.
Basically I was need it to work with database.
Like, we have following lists
- users list
- subjects list with user_id
- topics list with subject_id
- question list with subject_id
So, in HTML we will use data-list-id attribute with child list to make the list depend on parent list.
Attribute data-list-id contains the value of the parent list. like data-list-id of the subject list will contain the user_id and same with other lists.
What we are going to use here,
- Bootstrap form
- jQuery
- Custom jQuery snippet
HTML file will contain something like this,
<!-- Super Parent --> <div class="form-group"> <label for="first_list"> User select </label> <select class="form-control" id="first_list"> <option value="0"> Select User list </option> <option value="1"> User A </option> <option value="2"> User B </option> <option selected value="3"> User C </option> <option value="4"> User D </option> <option value="5"> User E </option> </select> </div> <!-- Parent: User list and Child: Subject list --> <div class="form-group"> <label for="second_list"> Subject select </label> <select class="form-control" id="second_list"> <option data-list-id="0" value="0"> Select subject list </option> <option data-list-id="1" value="1"> Subject A.1 </option> <option data-list-id="1" value="2"> Subject A.2 </option> <option data-list-id="1" value="3"> Subject A.3 </option> <option data-list-id="2" value="4"> Subject B </option> <option data-list-id="3" selected value="5"> Subject C </option> <option data-list-id="4" value="6"> Subject D </option> <option data-list-id="5" value="7"> Subject E </option> </select> </div>
Add following jQuery snippet
/** * Create dependable list with this function * @param {*} parentList-id * @param {*} childList-id */ function createDependableList(parentList, childList) { var options = $(childList+' option'); $(parentList).change( function() { $(childList).empty(); options.each((index, option)=> { if ( $(option).data('list-id') == this.value /* || $(option).data('list-id') == 0 */ ) { option.selected = option.selected ? true : false; $(childList).append(option); } $(childList).trigger('change'); }) if ( $(childList+' option').length === 0 ) { $(childList).append('<option value="">No option available..</option>'); } }) }
Use this createDependableList() function to create list chain.
like we have used in the example.
<script type="text/javascript"> createDependableList ( '#first_list', '#second_list' ); createDependableList ( '#second_list', '#third_list' ); createDependableList ( '#second_list', '#fourth_list' ); </script>
One more thing our snippet will also handle default selected option (if any) as per database values.
Bonus point, It can also handle multiple child lists with single parent list.
You can check our GitHub Repo.