Apu
September 06, 2022 .
#HowTo
.
#Javascript
❌
How to get dropdown selected text in JavaScript
To get the selected text from a drop down <select> using Javascript, we will select the <select> element using the querySelector() method and get its value using the value property.
Example : get text from drop down.
<select id="my-id">
<option>Drop down 1</option>
<option>Drop down 2</option>
<option>Drop down 3</option>
<option>Drop down 4</option>
</select>
<script>
const myVariable = document.getElementById('my-id')
document.write(myVariable.value)
</script>
Try it Yourself »
-
In the above example, I have created a <select> element
with four options and an id my-id.
<select id="my-id"> <option>Drop down 1</option> <option>Drop down 2</option> <option>Drop down 3</option> <option>Drop down 4</option> </select>
-
Using the Javascript's getElementById() method, I have select the
<select> element and store it in a variable
myVariable.
const myVariable = document.getElementById('my-id');
-
To display the select value , I have use the
write() method and the value property.
document.write(myVariable.value)
Get the value onchange.
If you want to display the selected value from a drop down, then you have to use the onchange attractive to the <select> element.
- We will add the onchange attribute to the <select> element and set a value myFunction(). So that, whenever someone will click on the <select> element and change its value, the myFunction() function is involved.
<select onchange="myFunction()"> <option>Drop down 1</option> <option>Drop down 2</option> <option>Drop down 3</option> <option>Drop down 4</option> </select>
- Now create the myFunction() function.
function myFunction(){ const myVariable = document.querySelector('select'); document.write(myVariable.value) }
Try it Yourself »
save
listen
AI Answer
How to get dropdown selected text in JavaScript
0
To get the selected text from a drop down <select> using
Javascript, we will s…
asked
Apu
0 answers
2915
To get the selected text from a drop down <select> using
Javascript, we will s…
Answer Link
answered
Apu