开发者

How to get the id of selected option in <select> in my case?

开发者 https://www.devze.com 2023-02-27 06:35 出处:网络
I have a < select > field and a button in index.html: <select id=\"mylist\"></select> <input 开发者_开发知识库type=\"button\" id=\"btn\" value=\"update\">

I have a < select > field and a button in index.html:

<select id="mylist"></select>

<input 开发者_开发知识库type="button" id="btn" value="update">

The following Javascript will update the options of the < select > field when button is clicked:

var btn=$('#btn');
btn.click(function(){
     var optionList = GET_OBJECT_LIST(); //get an array of Object, object has id & name
     var select  = $("#mylist");

     select.empty();

     for(var i=0; i<optionList.length; i++){
       select.append("<option value=" + optionList[i].id+ ">" + optionList[i].name + "</option>");
     }

});

Things are fine until now.

Then, I would like to implement the feature that after options are updated, when mouse click on an option in the <select> field, I can get the object id (i.e. the <option> value) of the selected option. How to do it?


This might work (not sure if it returns an array or not, so you'll find out):

$('#mylist').change(function() {
  var selected = $(this).find('option:selected');

  // Foo.
});


I figured out to use the following code which fits exactly what I want:

$('#mylist').change(function() {
  var selected_object_id = $(this).find('option:selected').attr('value');
  console.log(selected_object_id); //it directly returns to me the selected option represented object id
});
0

精彩评论

暂无评论...
验证码 换一张
取 消