【问题标题】:Dynamically selecting option in dropdown menu using jquery/javascript only working sometimes使用 jquery/javascript 在下拉菜单中动态选择选项有时仅有效
【发布时间】:2021-07-14 04:02:42
【问题描述】:

我目前正在尝试使用 jquery/javascript 填充下拉菜单并动态选择其中一个选项,但在设置选择状态时遇到了问题。

模态窗口:

  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <form id="editForm">
        <div class="modal-header">
          <h5 class="modal-title" id="myModalLabel">Edit User: <strong class="fullname"></strong></h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="container-fluid">
            <input type="hidden" class="id" name="id">
            <div class="row form-group">
              <div class="col-md-4">
                <div class="form-group bmd-form-group is-filled">
                  <label class="bmd-label-floating" for="roles">Site Role</label>
                  <!--Dropdown to be populated dynamically -->
                  <select class="form-control bmd-form-group is-filled roles" data-style="btn btn-link" id="edit_roles" name="roles"></select>
                </div>
              </div>
            </div>
            <!--Other inputs removed for clarity -->
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
          <button type="submit" class="btn btn-success"><i class="material-icons">check</i> Update</button>
        </div>
      </form>
    </div>
  </div>
</div>

JS:

//edit
$(document).on('click', '.edit', function(){
  
  var id = $(this).data('id');
  
  getRoles("edit");
  
  getDetails(id);
  
  $('#edit').modal('show');
});

$('#editForm').submit(function(e){
  e.preventDefault();
  var editform = $(this).serialize();
  $.ajax({
    method: 'POST',
    url: 'controllers/edit.php',
    data: editform,
    dataType: 'json',
    success: function(response){
      if(response.error){
        //Generate popup notification
        $.notify({
          message: response.message
        },{
          type: 'warning'
        });
        
      }
      else{
        //Generate popup notification
        $.notify({
          message: response.message
        },{
          type: 'success'
        });
        
        
        fetch();
      }
      $('#edit').modal('hide');
    }
  });
});
//



function fetch(){
  $.ajax({
    method: 'POST',
    url: 'controllers/fetch.php',
    success: function(response){
      $('#tbody').html(response);
    }
  });
}

function getDetails(id){
  $.ajax({
    method: 'POST',
    url: 'controllers/fetch_row.php',
    data: {id:id},
    dataType: 'json',
    success: function(response){
      //alert(JSON.stringify(response));
      if(response.error){
        $('#edit').modal('hide');
        $('#delete').modal('hide');
        $('#alert').show();
        $('#alert_message').html(response.message);
      }
      else{
        // Start populating the modal window with the user's details
        
        //*******For some reason this only works sporadically*******
        $('#edit_roles').val(response.data.u_rolecode);
        //$('.roles option[value=' + response.data.u_rolecode + ']').attr('selected','selected');
        
        $('.id').val(response.data.u_userid)
        $('.username').val(response.data.u_username);
        $('.password').val(response.data.u_password);
        $('.firstname').val(response.data.u_firstname);
        $('.lastname').val(response.data.u_lastname);
        $('.email').val(response.data.u_email);
        $('.jobtitle').val(response.data.u_jobtitle);
        $('.active').val(response.data.u_is_active);
        $('.created').val(response.data.u_create_at);
        $('.fullname').html(response.data.u_firstname + ' ' + response.data.u_lastname);
      }
    }
  });
}


function getRoles(prefix){
  $.ajax({
    method: 'POST',
    url: 'controllers/fetch_roles.php',
    success: function(response){
      $('#' + prefix +'_roles').html("<option value='0'>- Select -</option>" + response);
    }
  });
}

当有人尝试编辑用户的详细信息时,模式窗口会填充用户当前的详细信息,下拉列表会填充所有可用站点角色的列表,并且会动态选择用户的特定站点角色。

至少据我所知,对数据库的所有请求都是成功的——用户的数据全部返回并正确显示,所有可用站点角色的列表也返回并正确填充。

但是,实际上在该下拉列表中为用户的特定角色设置选定状态似乎偶尔会起作用。我尝试通过 ID 和类名设置状态,每次都具有相同的命中和未命中结果。

我注意到,通过快速打开和关闭模态编辑窗口,我更有可能“强制”这种情况发生,但它仍然会作为我认为非极端常规用法的一部分发生。

$('#edit_roles').val(response.data.u_rolecode); //$('.roles option[value=' + response.data.u_rolecode + ']').attr('selected','selected');

输出 #1:工作

输出 #2:不工作

(它一个下拉菜单,尽管引导程序使它看起来不是这样。)

任何建议将不胜感激。

【问题讨论】:

  • response.data.u_rolecode 的值是大写的,你能显示它的输出吗?
  • 您最好提供一些 jdFiddle 或 CodePen,以便我们轻松重现问题
  • 没有太多细节可以处理,但通常在这些情况下,问题在于代码的执行顺序。加载脚本的错误顺序也可能是问题所在。

标签: javascript html jquery ajax


【解决方案1】:

问题在于getRolesgetDetails 都是异步操作,这意味着无法保证哪个会先完成操作。

可能的解决方案:

  1. 使getRoles ajax 请求同步调用
  2. getRoles ajax 成功条件内调用getDetails(这也可以通过callback 实现)

编辑:我个人会选择第二个选项,因为它不会阻止/冻结页面。

【讨论】:

  • 谢谢。我怀疑这与异步操作有关,但是我没有正确设置的知识。结合上面@Thomson Mixab 给出的示例,我尝试了您的两个建议。正如预期的那样,上述两个建议都解决了这个问题。
  • @user6790086 我个人会选择第二个选项
【解决方案2】:

需要让getDetails页面同步调用返回响应数据。

function getDetails(id){
  $.ajax({
    method: 'POST',
    url: 'controllers/fetch_row.php',
    async: false,          // ***** you need to make synchonous call 
    data: {id:id},
    dataType: 'json',
    success: function(response){
      //alert(JSON.stringify(response));
      if(response.error){
        $('#edit').modal('hide');
        $('#delete').modal('hide');
        $('#alert').show();
        $('#alert_message').html(response.message);
      }
      else{
        // Start populating the modal window with the user's details
        
        //*******For some reason this only works sporadically*******
        $('#edit_roles').val(response.data.u_rolecode);
        //$('.roles option[value=' + response.data.u_rolecode + ']').attr('selected','selected');
        
        $('.id').val(response.data.u_userid)
        $('.username').val(response.data.u_username);
        $('.password').val(response.data.u_password);
        $('.firstname').val(response.data.u_firstname);
        $('.lastname').val(response.data.u_lastname);
        $('.email').val(response.data.u_email);
        $('.jobtitle').val(response.data.u_jobtitle);
        $('.active').val(response.data.u_is_active);
        $('.created').val(response.data.u_create_at);
        $('.fullname').html(response.data.u_firstname + ' ' + response.data.u_lastname);
      }
    }
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多