简体   繁体   中英

Select latest selected value of a dropdown

Is there a way to select the latest user's selected value of a dropdown?

Eg:

<select id="data" name="data" class="data" multiple="multiple">
    <option value="100">foo</option>
    <option value="101">bar</option>
    <option value="102">bat</option>
    <option value="103">baz</option>
</select>

If I use something like the bellow example, what I get is the last index, but it's not what I want.

var latest_value = $("option:selected:last",this).val();

What I want is something like: if you select "bar", I get 101, if you select "foo" I get 101 instead of 100.

OBS: all my examples are considering that the user is selecting multiple values, not just one.

Use this simple js code:

var is_now_selected = document.getElementById('data').value;

// or with jQuery

var is_now_selected = $('#data').val()

Maybe you don't know that the option -value accually is the value of the select . If you click <option value="something"> which is inside a <select name="select_me"> , then this select will have the value of the selected option - in this case - "select_me" .

You can write this code. It may help you.

Please let me know if you have anymore problem.

$("#data").change(function () {
    alert($("#data").val());
});

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