使用jQuery从<select>获取更改的值

Ani*_*ket 3 jquery

我试图<select>使用jQuery获取输入的更改值.

改变之前

<select class="input" multiple="multiple" name="inputUserRoles[]">
  <option value="Administrator">Administrator</option>
  <option value="Faculty" selected="selected">Faculty</option>
  <option value="Head of Department">Head of Department</option>
  <option value="Faculty Coordinator" selected="selected">Faculty Coordinator</option>
</select>
Run Code Online (Sandbox Code Playgroud)

改变之后

<select class="input" multiple="multiple" name="inputUserRoles[]">
  <option value="Administrator">Administrator</option>
  <option value="Faculty" selected="selected">Faculty</option>
  <option value="Head of Department">Head of Department</option>
  <option value="Faculty Coordinator">Faculty Coordinator</option>
</select>
Run Code Online (Sandbox Code Playgroud)

如果您注意到,在更改事件之后,"教师协调员"选项不是selected.

我希望获得"教师协调员"的价值.

我的javascript代码

$('select[name="inputUserRoles[]"]').change(function(e) {
  // this line gives me the value after the change event.
  var inputUserRoles = $(this).val();
});
Run Code Online (Sandbox Code Playgroud)

可能的解决方案?

我认为事件(e)应该包含已更改的数据,但我不知道如何获取它.我正在进行的项目正处于最后阶段,我只需要找出这一部分来完成类似的剩余模块.

完成此任务的另一种方法是获取旧输入并进行比较.

小智 6

去做:

var valueBeforeChange = $('select[name="inputUserRoles[]"]').val();

$('select[name="inputUserRoles[]"]').change(function(e) {
  var inputUserRoles = $(this).val();

  //you can compare here with value before change
  ...

  valueBeforeChange = inputUserRoles;
});
Run Code Online (Sandbox Code Playgroud)