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. What has caused this malfunction?
2
Answers
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:
That worked.
To get selected text on the change dropdown, you can use this jquery syntex
and to get a select value on the dropdown change you can use