skip to Main Content

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


  1. 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.

    $.ajax({
      url: "get_json_options.php",
      type: 'post',
      data: '',
      dataType: "json",
      async: true,
      //contentType: false,
      //cache: false,
      //processData: false,
      beforeSend: function() {
        //alert("before");
      },
      success: function(options) {
        console.log(options);
      },
      error: function(xhr, status, error) {
        console.log("Error in get_json_options.php:" + xhr.responseText);
      }
    }); //ajax
    
    Login or Signup to reply.
  2. One gets such search/filter behavior for free, if one utilizes an input control’s list attribute which points to the to be used/applied datalist element

    function retrieveAndApplyNameOptions() {
    
      const $datalist = $('datalist#name-options');
      const $selector = $('select#name-selector');
    
      // - e.g. retrieved from local storage like ...
      //   ... localStorage.getItem('name-options') 
      const jsonValue =
        '[{"id":3,"name":"Ann"},{"id":4,"name":"Karl"},{"id":31,"name":"Jess"}]';
    
      const nameOptions = JSON.parse(jsonValue);
    
      nameOptions.forEach(optionItem => {
        const { name } = optionItem;
    
        $datalist.append(`<option value="${ name }"></option>`);
        $selector.append(`<option value="${ name }">${ name }</option>`);
      });
    }
    
    $(document).ready(retrieveAndApplyNameOptions);
    body { margin: 0; }
    fieldset { margin: 10px 0; }
    <datalist id="name-options"></datalist>
    
    <form>
      <fieldset>
        <legend>Name via datalist options</legend>
    
        <label>
          <span data-label>Search for a name ...</span>
          <input name="name" list="name-options">
        </label>
      
      </fieldset>
      <fieldset>
        <legend>Name via select and options</legend>
    
        <label>
          <span data-label>Choose a name ...</span>
          <select name="name" id="name-selector"></select>
        </label>
      
      </fieldset>
    <form>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search