【问题标题】:dynamic dependent select box.. set to certain value动态依赖选择框..设置为某个值
【发布时间】:2021-04-04 14:53:20
【问题描述】:

我正在处理我在这里找到的这个脚本:https://www.webslesson.info/2020/04/dynamic-dependent-select-box-with-search-option-in-php-using-jquery-ajax.html 它工作正常。我想为类别项目设置一个特定的值。通常你会用选项值设置它。我看到这是脚本的一部分。所以例如..在数据库中,它被存储我们有城市和国家。因此,一旦我选择类别 Country -> England,它就会自动将所有城市(包括伦敦)列为子类别。如果稍后您想修改连接到英格兰 - 伦敦的用户记录。通过调出此脚本,您将不得不再次选择国家和城市。但我希望它说明英格兰 - >伦敦,而我可以选择布莱顿而不是伦敦。

          <div class="form-group">
            <label>Select Category</label>
            <select name="category_item" id="category_item" class="form-control input-lg" data-live-search="true" title="Select Category"></select>
          </div>
          <div class="form-group">
            <label>Select Sub Category</label>
            <select name="sub_category_item" id="sub_category_item" class="form-control input-lg" data-live-search="true" title="Select Sub Category"></select>
          </div>
          
          <script>
$(document).ready(function(){

  $('#category_item').selectpicker();

  $('#sub_category_item').selectpicker();

  load_data('category_data');

  function load_data(type, category_id = '')
  {
    $.ajax({
      url:"load_data.php",
      method:"POST",
      data:{type:type, category_id:category_id},
      dataType:"json",
      success:function(data)
      {
        var html = '';
        for(var count = 0; count < data.length; count++)
        {
          html += '<option value="'+data[count].id+'">'+data[count].name+'</option>';
        }
        if(type == 'category_data')
        {
          $('#category_item').html(html);
          $('#category_item').selectpicker('refresh');
        }
        else
        {
          $('#sub_category_item').html(html);
          $('#sub_category_item').selectpicker('refresh');
        }
      }
    })
  }

  $(document).on('change', '#category_item', function(){
    var category_id = $('#category_item').val();
    load_data('sub_category_data', category_id);
  });
  
});
</script>

【问题讨论】:

    标签: javascript php ajax


    【解决方案1】:

    您将需要选项标签的 id 或值。在您的情况下是 data[count].id。因此,要设置您将使用的值:

    $('#selector_id').value = data[count].id; // Id or the value of the option you want to set
    

    编辑:

    在您的特定情况下,这将像这样工作:

    $('#container_id').value = country_id; //2 for example for England
    $('#sub_container_id').value = city_id; //21 for example
    

    【讨论】:

    • 好吧。如果 country_id 是:2 和 city_id = 21.. 它会是这样的:$('#selector_id').value = 2;.. 然后城市会自动id: 21 也出现?
    • 只需将 data[count].id 分别替换为 2 和 21
    • 像这样:$('#country_selector_id').value = 2; // 更改 country_selector_id 与您的 html 中的相应 id
    • 你有两个不同的选择器,对吧?一个代表国家,一个代表城市。对吗?
    • 否...代码中只有一行是:html += '
    猜你喜欢
    • 1970-01-01
    • 2020-11-08
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多