I’m looking for a way to add filter/search to a dropdown menu that is dynamically filled from a local json file.
Here’s my script :
var json = [{
"id": 3,
"name": "Ann"
},
{
"id": 4,
"name": "Karl"
},
{
"id": 31,
"name": "Jess"
}
]
$(document).ready(function() {
for (i in json) {
$("#name-selector").append('<option id= "name-data" name="submit" type="submit" value="' + json[i]["name"] + '">' + json[i]["name"] + '</option>');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="div-selectors">
<h5>Name</h5>
<form>
<select value="false" name="name" id="name-selector" class="selectors">
<option value="">Select option</option>
</select>
</form>
</div>
I’ve tried to put add an input option in the dropdown menu put it places the input outside the dropdown menu.
Any idea how I could implement this ?
2
Answers
You can not store the JSON file locally on the client. The JSON file should live on the server. It looks like you are using jQuery so I would use AJAX to write the JSON file to the server or read from the server.
Here is an example that will read the JSON file via a PHP script that you have to write. Research AJAX examples.
One gets such search/filter behavior for free, if one utilizes an input control’s
list
attribute which points to the to be used/applieddatalist
element …