How to get <select> options (value or text) using jQuery

I have a code for

<select id='list'>
    <option value='1'>Option A</option>
    <option value='2'>Option B</option>
    <option value='3'>Option C</option>
</select>

and I want to ever select any parameter, it will be displayed in a warning message. I tried

<script type='text/javascript'>

    //var value = $("#list option[value=2]").text();
    //var value = $("#list option:selected").text();
    //var value = $('#list').val();
    var value = $(this).val();
    alert(value);

</script>

but fail.

+3
source share
4 answers

Thanks to Sarfras Ahmed

but mistakenly forgot to add # ie:

$('#select_box_id').change(function(){
    alert($(this).text());
});

thanks again to Yar.

+2
source

Add the name attribute to the select tag.

Example:

<script type="text/javascript">
    $(document).ready(function() {
        $("#list").change(function() {
            var k = $("#list option[value=" + $(this).val() +"]").text();
            alert(k);
        });
    });
</script>

HTML

<select id="list" name="list">
    <option value="1">Option A</option>
    <option value="2">Option B</option>
    <option value="3">Option C</option>
</select>
0
source

Try the following:

$('#select_box_id').change(function(){
   alert($(this).val());
 });
0
source

Not much easier than that. Also optimized for speed.

$("select#list").change(function() {
    alert($("> option:selected", this).text());
});
0
source

Source: https://habr.com/ru/post/1725941/


All Articles