如何使用jQuery或js传递数据/值以选择选项?

时间:2019-02-01 14:08:55

标签: javascript jquery select

 <select id="scStatus{{sid.id}}" name="statusclass" class="selectpicker nk-int-st statusclass">
                                            <option selected value=""></option>
                                            <option value="Active">Active</option>
                                            <option value="Suspended">Suspended</option>
                                        </select>

添加了选择选项,我想使用我尝试过的jquery或js更改值

$('.statusclass').val(data.job_status); 
 $('.statusclass').change();

 document.getElementsByClassName('statusclass')[0].value = data.job_status

           $('.statusclass option[value="' + data.job_status + '"]').attr("selected", "selected");

ere

1 个答案:

答案 0 :(得分:0)

说实话,要弄清楚您所拥有的代码有什么问题有点困难。假设您输入有效的选项值,.val()应该可以正常工作。

演示(单击“运行代码段”,然后单击标记为“单击以更改值”的按钮以查看实际效果):

$(function() {
  $("#btn").click(function() {
    var data = {
      "job_status": "Active"
    };
    $('.statusclass').val(data.job_status);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="scStatus{{sid.id}}" name="statusclass" class="selectpicker nk-int-st statusclass">
  <option selected value=""></option>
  <option value="Active">Active</option>
  <option value="Suspended">Suspended</option>
</select>
<button type="button" id="btn">Click to change value</button>