Home > Software engineering >  Get selected option from select list
Get selected option from select list

Time:08-20

I have the following select list and jQuery code to dynamically get the selected option:

<select id="form_instructions_instruction_select" name="form[instructions][instruction_select]">
    <option value="-- select --"></option>
    <option value="new">new</option>
    <option value="35">first intruction test</option>
    <option value="47">testing</option>
    <option value="45">testing ... testing</option>
    <option value="48">test</option>
    <option value="49">testing new instruction</option>
</select>

$(document).ready( () => {
    $('select#form_instructions_instruction_select').on('change', () => {
        console.log( $(this).text() );
        console.log( $(this).value() );
    });
});

But the text console output returns an empty string and the value output returns the following:

Uncaught TypeError: $(...).value is not a function

I found some answers suggesting to query the select list for the option with the option:selected attribute. But there is no option with such an attribute whenever I select a different option.

The irony is that my code worked correctly and as expected previously. I'm not sure what has caused this malfunction.

I would appreciate some help.

CodePudding user response:

To get selected text on the change dropdown, you can use this jquery syntex

$(this).find("option:selected").text()

and to get a select value on the dropdown change you can use

$(this).val()

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
 $(document).ready(function(){
  $('select#form_instructions_instruction_select').on("change",function(){
  alert("Text:-"   $(this).find("option:selected").text()   " and value:-"  $(this).val())
    })
 });
</script>
</head>
<body>
<select id="form_instructions_instruction_select" name="form[instructions][instruction_select]">
    <option value="-- select --"></option>
    <option value="new">new</option>
    <option value="35">first intruction test</option>
    <option value="47">testing</option>
    <option value="45">testing ... testing</option>
    <option value="48">test</option>
    <option value="49">testing new instruction</option>
</select>

</body>
</html>

CodePudding user response:

I fully conceed that $(this).find("option:selected").val() ought to work but I don't know why it didn't for me.

Eventually, I thought about attempting a plain JS approach and came up with the following:

document.getElementById('form_instructions_instruction_select').addEventListener('change', (event) => {
    console.log(event.target.value);
})

That worked.

  • Related