【问题标题】:Select option does not set the selected value from a response选择选项不会从响应中设置选定的值
【发布时间】:2018-07-25 10:08:19
【问题描述】:

我有 2 个选择下拉列表,我用来自服务器的值填充这些下拉列表。我可以毫无问题地检索值并填充选择下拉列表的选项,但是,当我尝试将第二个选择下拉列表的值之一设置为选定值时,它不会显示。

这是我的代码:

$.ajax({
   type: "GET",
   url: "/someUrl",
   data: { nameType: 'Shop', item: itemName},
       success: function (data) 
       {
         $.each(data, function (i, obj) {

           var div_data = "<option>" + obj.Shop + "</option>";
           $(div_data).appendTo('#shop_name');
         });


                $.ajax
                ({
                    url: '/get_shop_item',
                    type: 'POST',
                    data: { shop_id: shop_id },
                    success: function (response) 
                    {

                        $('#area_name option').filter(function() {
                            return this.text == response.result[0].area;
                        }).attr('selected', true);

                        $('#shop_name option').filter(function() {
                            return this.text == response.result[0].name;
                        }).attr('selected', true);
                    }
                });
           }
     });

【问题讨论】:

    标签: node.js ajax express


    【解决方案1】:

    您发布的代码仅填充一个选择元素#shop_name

    我可能会在选项上设置 name 属性,然后您不必使用 filter 并浏览所有选项。

    试试这个

    $.ajax({
       type: "GET",
       url: "/someUrl",
       data: { nameType: 'Shop', item: itemName},
           success: function (data) {
             $.each(data, function (i, obj) {
               var div_data = '<option name="' + obj.Shop + '">' + obj.Shop + '</option>';
               $(div_data).appendTo('#shop_name');
    
               // append to #area_name as well
             });
    
    
             $.ajax({
                 url: '/get_shop_item',
                 type: 'POST',
                 data: { shop_id: shop_id },
                 success: function (response) {
                    $('#area_name option[name="' + response.result[0].area + '"]').attr('selected', true);
    
                    $('#shop_name option[name="' + response.result[0].name + '"]').attr('selected', true);
                 }
             });
          }
      });
    

    【讨论】:

      猜你喜欢
      • 2018-09-12
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      相关资源
      最近更新 更多