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" 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.
CodePudding user response:
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:
- no need to call the AJAX, if there's nothing inside the first
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 handler - the AJAX call contains a predefined
dataType
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 - instead of using
$.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:
$.ajax({
// your ajax setup
}).done(function(data){
if(data) {
$("#entityName").html(data);
} else {
$("#entityName").html('<option value="" disabled selected>Select Entity Type First</option>');
}
dselect($("#entityName")[0], { search: true });
});
- the example also uses
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
$(document).ready(function(){
const config = {
search: false, // Toggle search feature. Default: false
creatable: false, // Creatable selection. Default: false
clearable: false, // Clearable selection. Default: false
maxHeight: '360px', // Max height for showing scrollbar. Default: 360px
size: '', // Can be "sm" or "lg". Default ''
}
dselect($("#entityName")[0], config);
$("#entityType").change(function(){
let entityType = $(this).val();
if(!entityType) {
$("#entityName").html('<option value="" disabled selected>Select Entity Type First</option>');
dselect($("#entityName")[0], config);
return false;
}
$.ajax({
type: "GET",
url: "https://pokeapi.co/api/v2/type/" entityType,
dataType: "json",
success: function(data) {
let pokemon = data.pokemon;
let pokeList = '<option value="" selected>Please choose your Pokemon</option>';
console.log(pokemon[0].pokemon.name);
for(var i = 0; i < pokemon.length; i ) {
let pokeName = pokemon[i].pokemon.name;
let pokeUrl = pokemon[i].pokemon.url;
pokeList = '<option value="' pokeUrl '">' pokeName '</option>';
}
$("#entityName").html(pokeList);
dselect($("#entityName")[0], config);
},
error: function(desc, err) {
alert("Error: " JSON.stringify(desc) ", " JSON.stringify(err));
}
});
});
});
label {
margin-left: 15px;
}
#entityType {
margin: 15px 0 15px 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@jarstone/dselect/dist/css/dselect.css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC nuZB EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
<script src="https://unpkg.com/@jarstone/dselect/dist/js/dselect.js"></script>
<label for="entityType">Select Entity Type:</label>
<select id="entityType" name="entityType" required>
<option value="">Choose</option>
<option value="water">Water</option>
<option value="fire">Fire</option>
<option value="ground">Ground</option>
<option value="electric">Electric</option>
<option value="flying">Flying</option>
</select>
<select id="entityName" name="entityName" required>
<option value="" disabled selected>Select Entity Type First</option>
</select>
<div id="list"></div>
CodePudding user response:
}).done(function(data){
$("#entityName").html(data);
dselect($("#entityName")[0], { search: true });
});
Example - you need to add some CSS I think
const $select_box_element = $('#entityName');
const $entity = $('#entityType');
$("select.entity").change(function(){
if (this.value === "one") {
$select_box_element.html(`<option value="one">One</option><option value="oneone">OneOne</option>`)
dselect($select_box_element[0], { search: true });
}
else {
$select_box_element.html(`<option value="two">Two</option><option value="twotwo">TwoTwo</option>`)
dselect($select_box_element[0], { search: true });
}
});
dselect($entity[0], { search: true });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@jarstone/dselect/dist/css/dselect.css">
<script src="https://unpkg.com/@jarstone/dselect/dist/js/dselect.js"></script>
<label>Select Entity Type:</label>
<select id="entityType" name="entityType" required>
<option value="" disabled selected>Select Entity Type</option>
<option value="one">One</option>
<option value="two">Two</option>
</select>
<label>Select Entity Name:</label>
<select id="entityName" name="entityName" required>
<option value="" disabled selected>Select Entity Type First</option>
<option value="one">One</option>
<option value="one">One</option>
</select>