如何根据从AJAX获取的JSON数据禁用选择选项?

kyo*_*kyo 6 html javascript ajax jquery json

我有一个带有几个选项的下拉菜单.我想循环遍历它们并支持其中disabled一些属性基于Ajax调用的结果.

在此输入图像描述

这就是我想要实现的目标.

在此输入图像描述


可报告数据样本

s-00591 | true
s-00592 | false
s-00593 | false
s-00594 | false
s-00595 | false 
Run Code Online (Sandbox Code Playgroud)

HTML

<select class="rn-dropdown" id="rn-dd">
    <option value="class-view">class view</option>
    <!-- Students Populate Here  -->
    <option value="s-00591">Student S00591</option>
    <option value="s-00592">Student S00592</option>
    <option value="s-00593">Student S00593</option>
    <option value="s-00594">Student S00594</option>
    <option value="s-00595">Student S00595</option>
</select>
Run Code Online (Sandbox Code Playgroud)

JS

success: function(reportable) {



    $.each(reportable , function(i, v) {

        var userId = v.userId;
        var reportable = v.reportable;
        var currentVal = userId;

        console.log('start');
        console.log(userId + " | " +reportable);
        $('#rn-dd option[value="' + currentVal + '"]').prop('disabled', true);
        console.log('end');

    });



}
Run Code Online (Sandbox Code Playgroud)

结果,

我没有显示控制台的错误.但我一直看到我的下拉菜单没有被禁用,因为我想要它们.

在此输入图像描述

任何提示/帮助/建议对我来说都意味着很多.

fuy*_*oya 1

  1. .prop('disabled', true);我相信这是一个拼写错误或其他什么原因,因为它禁用了所有选项。

  2. jsonObj 中的true,​​ 值可能是。因此,无论值为或,其处理方式为,因此始终为 false,这意味着它不会禁用任何选项。falseString'true''false'true!reportable

您可能必须先检查它是否是字符串,例如:

reportable = (typeof v.reportable === 'string') ? v.reportable === 'true' : v.reportable
Run Code Online (Sandbox Code Playgroud)

首先将其转换为布尔值。

reportable = (typeof v.reportable === 'string') ? v.reportable === 'true' : v.reportable
Run Code Online (Sandbox Code Playgroud)
var reportable = [
  {userId: 's-00591', reportable: 'true'},
  {userId: 's-00592', reportable: 'false'},
  {userId: 's-00593', reportable: 'false'},
  {userId: 's-00594', reportable: 'false'},
  {userId: 's-00595', reportable: 'false'}
];

// Check the diff between string and boolean.
var reportable2 = [
  {userId: 's-00591', reportable:  true},
  {userId: 's-00592', reportable: false},
  {userId: 's-00593', reportable: false},
  {userId: 's-00594', reportable: false},
  {userId: 's-00595', reportable: false}
];



$.each(reportable , function(i, v) {
  var userId = v.userId;
  var reportable = v.reportable;
  var currentVal = userId;

  console.log('start');
  console.log(userId + " | " +reportable);
  $('#rn-dd option[value="' + currentVal + '"]').prop('disabled', !reportable);
  console.log('end');

});

$.each(reportable2 , function(i, v) {
  var userId = v.userId;
  var reportable = v.reportable;
  var currentVal = userId;

  console.log('start');
  console.log(userId + " | " +reportable);
  $('#rn-dd2 option[value="' + currentVal + '"]').prop('disabled', !reportable);
  console.log('end');

});
Run Code Online (Sandbox Code Playgroud)