选择选项不会设置响应中的选定值

时间:2018-07-25 01:11:44

标签: node.js ajax express

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

这是我的代码:

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

1 个答案:

答案 0 :(得分:0)

您发布的代码仅填充一个选择元素#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);
             }
         });
      }
  });