Populate Select Options From JSON Data With jQuery - selectfromjson

File Size: 7.19 KB
Views Total: 3908
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Populate Select Options From JSON Data With jQuery - selectfromjson

selectfromjson is a tiny and developer-friendly jQuery select box enhancement plugin that makes it possible to populate the options of a select dropdown list from a JSON data via AJAX requests.

How to use it:

1. Load the minified version of the selectfromjson plugin from the dist folder.

<script src="/path/to/cdn/jquery.min.js"></script>
<script src="/path/to/dist/js/jquery.jsonselect.min.js"></script>

2. Add the following data attributes to your empty select element.

  • data-url: path to the JSON file
  • data-autoload: auto loads data on init
  • data-value: key of JSON data (used to fill the option's value)
  • data-text: key of JSON data ( used to fill the option's text)
<select name="select-1" 
        id="select-1"
        data-url="provinces.json" 
        data-autoload="true" 
        data-value="country" 
        data-text="name">
 </select>

3. You're also allowed to create a dependent select box where options are only populated when an option is selected in the parent select.

  • data-parent: parent select element
  • data-autoload: must be 'false'
<select name="select-2" 
        id="select-2"
        data-url="provinces.json" 
        data-autoload="false" 
        data-parent="#select-1"
        data-value="country" 
        data-text="name">
 </select>

4. Call the function jsonselect on the select element and the plugin will do the rest.

$("#select-1, #select-2").jsonselect({
  // options here
});

5. Customize the placeholder text.

$("#select-1, #select-2").jsonselect({
  empty_text: 'Select Here...'
});

6. Available callback functions that will be called on success, error, or before send.

$("#select-1, #select-2").jsonselect({
  events: {
    success: function() { console.log('success fired!') },
    beforeSend: function() { console.log('beforeSend fired!') },
    error: function() { console.log('error fired!') }
  }
});

This awesome jQuery plugin is developed by nonDeath. For more Advanced Usages, please check the demo page or visit the official website.