简体   繁体   中英

How to get the currently selected option of a dom modified select box?

I'm using a fake select box in my script which means the original select box is hidden and for styling purposes a ul is showing up. Whenever the selected value of this list changes the orginal select box does too.

There is a change function for that. Within that function is following code:

var el = $(e.currentTarget) ;
$('#my_select_box').children().removeAttr('selected');
$('#my_select_box  option[value="'+el.attr('data-value')+'"]').attr('selected','selected');

After that change I want to retrieve the new selected value of the original select box in another function.

But the normal selector only gets the original value, not the new:

$('#my_select_box option:selected').val() //returns the wrong value

So how to I get the new value in the function I need it?

I tried this function:

$("#my_select_box").bind("DOMSubtreeModified", function() {
    console.log($(this).find('option:selected').val());    
});

It returns the correct value but not where I need it. So how can I retrieve the correct select box value out of the domtree live?

Thanks in advance!

instead of .attr('selected','selected'); , try .prop('selected', true);

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