Get changed value from <select> using jQuery

扶醉桌前 提交于 2021-02-04 16:19:08

问题


I am trying to get the changed value of a <select> input using jQuery.

Before change

<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>

After change

<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>

If you notice, after the change event, the option 'Faculty Coordinator' is not selected.

I wish to get the value 'Faculty Coordinator'.

My javascript code

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

Possible Solutions?

I was thinking that the event (e) should be containing the changed data but I have no idea how to get it. The project I am working on is in its final phase and I just need to figure out this part to complete the similar remaining modules.

The other way to get this done is by getting the old input and comparing.


回答1:


Do that:

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;
});


来源:https://stackoverflow.com/questions/11664399/get-changed-value-from-select-using-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!