I have a select box which options are coming from database depending on another selected option using ajax
$(document).ready(function(){
$("select.entity").change(function(){
var selectedEntity = $(".entity option:selected").val();
$.ajax({
type: "POST",
url: "entityName.php",
data: { entity : selectedEntity }
}).done(function(data){
$("#entityName").html(data);
});
});
});
// This is the select box where options are dynamic.
<label>Select Entity Name:</label>
<select id="entityName" name="entityName" class="select_box" required>
<option value="" disabled selected>Select Entity Type First</option>
</select>
This works fine but now i want a search box for the options. I am using this function for search.
var select_box_element = document.querySelector('.select_box');
dselect(select_box_element, {
search: true
});
As options are dynamic and loaded after the page load that’s why this function doesnot work.
I need to push dynamic options into dselect function based on the selection.
2
Answers
I use
$("#entityName")[0]
to get at the DOM element from the jQuery ObjectExample – you need to add some CSS I think
Something like this might work for you. I’ve used CSS and JS for the dselect library, as shown in the official GitHub repo. In the example, Bootstrap 5 files are also included, since dSelect seems to be relying on Bootstrap 5 files.
The API used is from the free Pokemon API.
Some notes on the slight rewriting on how the AJAX is handled:
select
element, and if we revert to the default#entityType
value. We just need to clear the previous contents of the#entityName
. That is what theif
does right inside thechange
event handlerdataType
attribute. This was done because I know in advance that theresponse
in my example (response of Pokemon API) will be in JSON format. You can also do that in your specific case, if you control the back-end / the wayentityName.php
works and outputs its results. If you don’t have that kind of control, you may want to omit this AJAX config parameter, and handle the results differently$.ajax({...}).done(...)
, the example uses separatesuccess
anderror
handlers. This was just a preference choice. For differences between the use ofsuccess
anddone
, please refer to this SO answer. In your specific case,.done(...)
would have worked as well, with additional testing if the receiveddata
matches what you expect it to match, like this:config
, as shown in the official GitHub repo. Again, if you’re happy with the way you’re initializing yourdselect
, you can skip the configuration