Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jquery选择选项删除初始选项并替换为其他选项_Jquery_Ajax - Fatal编程技术网

jquery选择选项删除初始选项并替换为其他选项

jquery选择选项删除初始选项并替换为其他选项,jquery,ajax,Jquery,Ajax,下面是jquery,它通过ajax向select输入添加了新选项。然而,select最初有一个选项,我想删除它,然后用通过ajax返回的选项替换它 $(document).ready(function () { $('#id_previous_postcode').change(function () { var postcode = $(this).val() console.log(postcode) $.ajax({ // could prevent

下面是jquery,它通过ajax向select输入添加了新选项。然而,select最初有一个选项,我想删除它,然后用通过ajax返回的选项替换它

$(document).ready(function () {
  $('#id_previous_postcode').change(function () {
    var postcode = $(this).val()
    console.log(postcode)
    $.ajax({
      // could prevent url hard coding by using url tag in form widget attribute and assign url key here to that attr
      url: '/users/prior_addresses_ajax/',
      data: {
        'postcode': postcode
      },
      dataType: 'json',
      success: function (data) {
        var select = document.querySelector('#id_previous_full_address');
        console.log(data)
        data.property_choices.forEach(function (subarray) {
          var option = new Option(subarray[1], subarray[0]);
          select.options.add(option);
        });
      }
    })
  })
})

在使用jQuery时,您可以选择

success: function (data) {

        // Will remove previous set options from select
        $('#id_previous_full_address').empty();

        var select = document.querySelector('#id_previous_full_address');
        console.log(data)
        data.property_choices.forEach(function (subarray) {
          var option = new Option(subarray[1], subarray[0]);
          select.options.add(option);
        });
      }
我建议使用

$("SELECTOR").first().detach();
然后

$("NEW ELEMENT").preppendTo($("SELECTOR").first().parent());

您能在触发jQuery之前发布选择器的外观吗?