简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM