我尝试了下面的代码行,如果与数据的DepartmentName匹配的选项被选中。没用请帮忙 !!!

         function fillDepartments(selectedText)
  {
        $.ajax({
                    url: 'index.php?action=fetchAllDepartments',
                    type: 'POST',
                    dataType: 'JSON',
                    data:{},
                    success: function(data){
                        for(var i in data){
                                $('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '">'
                                  + data[i]['DepartmentName'] + selectedText == data[i]['DepartmentName'] ? "selected" : "" +
                                 '</option>');
                            }
                     }
              });
  }

最佳答案

应用简单的if-else条件:-

for(var i in data){
    if(selectedText == data[i]['DepartmentName']){
        $('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '" selected>'+ data[i]['DepartmentName']+'</option>');
    }else{
        $('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '">'+ data[i]['DepartmentName'] +'</option>');
    }
}

关于javascript - 使在ajax调用中选择的选项无效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49231957/

10-10 01:34