使用jquery从json数据文件动态填充select元素

时间:2016-02-17 06:56:18

标签: javascript jquery json combobox

我正在尝试为州和地区创建搜索框,但我已启用将数据提取到组合框中。

我已经尝试了很多其他方法将数据输入到他们无法工作的选择框中。以下是我目前的代码:

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);

4 个答案:

答案 0 :(得分:1)

尝试:

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

答案 1 :(得分:1)

在您的上述代码中,您犯了以下错误,

1.Extra close bracket

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

将其更新为

    $.map(jsonList, function (el, i) {
        return $('<option>').val(el.slno).text(el.state)
    });
  1. 循环json对象

    $.map(jsonList.listval, function (el, i) {
            $('#state_id').append('<option value="'+el.slno+'" attState="'+el.state+'">'+el.state+'</option>');            
    });
    
  2. 为避免多次相同的状态重复,在插入选项之前,您需要检查条目是否已存在于选项中(如果不存在),然后将其添加到选择中,为此我引入了一个新选项属性&#34 ; attState&#34 ;.请查看您将了解我所做的代码。

    $.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>');
        }
    });
    

    供参考refer

答案 2 :(得分:1)

您可以执行以下操作(查看使用underscorejs的较短版本的修订历史记录):

评论应该可以帮助你了解一下。检查https://api.jquery.com/以获取有关所使用的jQuery方法的详细信息。

$(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>

答案 3 :(得分:0)

试试这个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);


});