Populate select elements dynamically from json data file using jquery

▼魔方 西西 提交于 2021-02-10 14:10:10

问题


I'am trying to create search box for state districts and villages , but I'am enable to fetch data into combobox.

I have tried so many other way to get data into select boxes they doesn't work. Below is the code I've so far:

HTML:

<div class="dummy__item">
  <select name="state_id" id="state_id" tabindex="1">
    <option value="">-- Select state --</option>


  </select>
</div>
<div class="dummy__item">
  <select name="district_id" id="district_id" tabindex="2">
    <option value="">-- Select district --</option>
  </select>
</div>
<div class="dummy__item">
  <select name="village_id" id="village_id" tabindex="3">
    <option value="">-- Select village --</option>
  </select>
</div>

JS:

<!-- language: lang-js -->

function loadlist(selobj, url) {
  $(selobj).empty();
  $(selobj).append('<option value="0">--Select Category--</option>')
  $(selobj).append(
    $.map(jsonList, function(el, i) {
      return $('<option>').val(el.slno).text(el.state)
    }));
}
loadlist($('select#state_id').get(0), jsonList);

回答1:


You can do the following (Check the revision history for a shorter version which made use of underscorejs):

The comments should help you get an idea. check https://api.jquery.com/ for detailed information regarding the jQuery methods used.

$(function() {
  insert($('#state_id'), plucker(records, 'state'));
  //------------------------^ grabs unique states
  //--^ populate state list on DOM ready
  $('select').on('change', function() {
    var category = this.id.split('_id')[0];
    var value = $(this).find('option:selected').text();
    switch (category) {
      case 'state':
        {
          insert($('#district_id'), plucker(filter(records, 'state', value),'district'));
          //-^ insert plucked results to DOM
          //------------------------^ plucks districts from filter results
          //--------------------------------^ filters districts belonging to selected state
          break;
        }
      case 'district':
        {
          insert($('#village_id'), plucker(filter(records, 'district', value),'village'));
          break;
        }
    }
  });

   function plucker(arr, prop) {
   // grabs unique items from the required property such as state,  district etc from the results
    return $.map(arr, function(item) {
      return item[prop]
    }).filter(function(item, i, arr) {
       return arr.indexOf(item) == i;
    });
  }

  function filter(arr, key, value) { 
    // filters the records matching users selection
    return  $.grep(arr, function(item) {
         return item[key] == value;
    });
  }

  function insert(elm, arr) { // inserts the results into DOM
    elm.find('option:gt(0)').remove();
    $.each(arr, function(i,item) {
      elm.append($('<option>', {
        value: i,
        text: item
      }));
    });
  }
});

var records = [{
  "slno": "1",
  "state": "Maharashtra",
  "constituency": "Parbhani",
  "mp": "Shri Sanjay Haribhau Jadhav",
  "district": "Parbhani",
  "block": "Jintur",
  "village": "Kehal",
  "latitude": "77.7",
  "longitude": "19.33"
}, {
  "slno": "2",
  "state": "Maharashtra",
  "constituency": "Shirur",
  "mp": "Shri Shivaji Adhalrao Patil",
  "district": "Pune",
  "block": "Shirur",
  "village": "Karandi",
  "latitude": "77.7",
  "longitude": "19.33"
}, {
  "slno": "3",
  "state": "Maharashtra",
  "constituency": "Amravati",
  "mp": "Shri Anandrao Vithoba Adsul",
  "district": "Amravati",
  "block": "Amravati",
  "village": "Yavli Shahid",
  "latitude": "77.7",
  "longitude": "19.33"
}]
$(function() {
  insert($('#state_id'), plucker(records, 'state'));
  //------^ populate states list on DOM ready

  $('select').on('change', function() {
    var category = this.id.split('_id')[0];
    var value = $(this).find('option:selected').text();
    switch (category) {
      case 'state':
        {
          insert($('#district_id'), plucker(filter(records, 'state', value), 'district'));
          break;
        }
      case 'district':
        {
          insert($('#village_id'), plucker(filter(records, 'district', value), 'village'));
          break;
        }
    }
  });


  function plucker(arr, prop) {
    // grabs unique items from the required property such as state, district etc from the results
    return $.map(arr, function(item) {
      return item[prop]
    }).filter(function(item, i, arr) {
      return arr.indexOf(item) == i;
    });
  }

  function filter(arr, key, value) {
    // filters the records matching users selection
    return $.grep(arr, function(item, i) {
      return item[key] === value;
    });
  }

  function insert(elm, arr) {
    // inserts the results into DOM
    elm.find('option:gt(0)').remove();
    $.each(arr, function(i, item) {
      elm.append($('<option>', {
        value: i,
        text: item
      }));
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dummy__item">
  <select name="state_id" id="state_id" tabindex="1">
    <option value="">-- Select state --</option>
  </select>
</div>
<div class="dummy__item">
  <select name="district_id" id="district_id" tabindex="2">
    <option value="">-- Select district --</option>
  </select>
</div>
<div class="dummy__item">
  <select name="village_id" id="village_id" tabindex="3">
    <option value="">-- Select village --</option>
  </select>
</div>



回答2:


In your above code you have made the following mistake,

1.Extra close bracket

    $.map(jsonList, function (el, i) {
        return $('<option>').val(el.slno).text(el.state)
    }));

Update it as

    $.map(jsonList, function (el, i) {
        return $('<option>').val(el.slno).text(el.state)
    });
  1. The looping of json object

    $.map(jsonList.listval, function (el, i) {
            $('#state_id').append('<option value="'+el.slno+'" attState="'+el.state+'">'+el.state+'</option>');            
    });
    

To avoid multiple times the same state repetition, before inserting the option you need to check if the entry is already exist in option if not exist then add it to the select, for this I have introduced a new option attribute "attState". Please look in to the code you will understand what I have done..

$.map(jsonList.listval, function (el, i) {
    if ($("#yourSelect option[attState='" + el.state + "']").length == 0) {
        $('#yourSelect').append('<option value="' + el.slno + '" attState="' + el.state + '">' + el.state + '</option>');
    }
});

For reference refer




回答3:


Try:

function createOptiolist(list, name) {
  var state = list.map(function(obj) {
    return obj[name];
  });
  return state = state.filter(function(v, i) {
    return state.indexOf(v) == i;
  });

}

var state = createOptiolist(jsonList.listval, "state");
$.each(state, function(i, el) {
  $('#state_id').append('<option value="' + el + '">' + el + '</option>');
});
$('#state_id').on('change', function() {
  var state = $(this).find('option:selected').val();
  $('#district_id').empty();
  $.each(jsonList.listval, function(i, el) {
    if (el.state == state) {
      $('#district_id').append('<option value="' + el.district + '">' + el.district + '</option>');
    }
  })
});
$('#district_id').on('change', function() {
  var district = $(this).find('option:selected').val();
  $('#village_id').empty();
  $.each(jsonList.listval, function(i, el) {
    if (el.district == district) {
      $('#village_id').append('<option value="' + el.slno + '">' + el.village + '</option>');
    }
  })
});

DEMO

DEMO with ajax




回答4:


Try this plz

HTML

<div class="dummy__item">
    <select name="state_id" id="state_id" tabindex="1">
        <option value="">-- Select state --</option>


    </select>
</div>

<div class="dummy__item">
    <select name="district_id" id="district_id" tabindex="2">
        <option value="">-- Select district --</option>
    </select>
</div>
<div class="dummy__item">
    <select name="village_id" id="village_id" tabindex="3">
        <option value="">-- Select village --</option>
    </select>
</div>

JQUERY

$(document).ready(function(){
            // JSON list
var jsonList = {"listval" : [
{
    "slno": "1",
    "state": "Maharashtra",
    "constituency": "Parbhani",
    "mp": "Shri Sanjay Haribhau Jadhav",
    "district": "Parbhani",
    "block": "Jintur",
    "village": "Kehal",
    "latitude": "77.7",
    "longitude": "19.33"
},
{
    "slno": "2",
    "state": "Maharashtra",
    "constituency": "Shirur",
    "mp": "Shri Shivaji Adhalrao Patil",
    "district": "Pune",
    "block": "Shirur",
    "village": "Karandi",
    "latitude": "77.7",
    "longitude": "19.33"
},
{
    "slno": "3",
    "state": "TEXAS",
    "constituency": "XYZ",
    "mp": "Shri ABC",
    "district": "dist1",
    "block": "block1",
    "village": "Yavli Shahid",
    "latitude": "77.7",
    "longitude": "19.33"
},
{
    "slno": "4",
    "state": "Maharashtra",
    "constituency": "Amravati",
    "mp": "Shri Anandrao Vithoba Adsul",
    "district": "Amravati",
    "block": "Amravati",
    "village": "Yavli Shahid",
    "latitude": "77.7",
    "longitude": "19.33"
}]}
// JSON LIST


function loadlist(selobj, url) {
    var categories = [];
    $(selobj).empty();
    $(selobj).append('<option value="0">--Select Category--</option>')
    $(selobj).append(

    $.map(jsonList.listval, function (el, i) {

     if ($.inArray(el.state, categories)==-1) {

    categories.push(el.state);
        return $('<option>').val(el.slno).text(el.state);
        console.log($(el.state));}
    }));
}


 loadlist($('#state_id').get(0), jsonList);


});


来源:https://stackoverflow.com/questions/35449881/populate-select-elements-dynamically-from-json-data-file-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!