Reputation: 11
i have dropdown in html and i have an dictionary in back-end to get key. since the dropdown is dynamically created so user keep adding to it.
<select id="cars">
<option>Volvo</option>
<option>Saab</option>
<option>Opel</option>
<option>Audi</option>
</select>
now since there is no value attribute like
<option value="volvo">Volvo</option>
how i can get the name of option using onchange attribute when user select
<option>Saab</option>
javascript should be able to get Saab and insert it b/w h1 tag
document.querySelector('#cars').onchange=function(){
document.querySelector('h1').innerHTML = //what to enter
// here to fetch get name of option currently selected.
};
<h1><h1>
Upvotes: 1
Views: 272
Reputation: 1153
document.querySelector('#cars').onchange=function(){
document.querySelector('h1').innerHTML = this.options[this.selectedIndex].value
};
<select id="cars">
<option>Volvo</option>
<option>Saab</option>
<option>Opel</option>
<option>Audi</option>
</select>
<h1><h1>
Upvotes: 0
Reputation: 207901
You just need this.value
as this
refers to the select and when options have no specified value, their content becomes the value by default.
document.querySelector('#cars').onchange = function() {
document.querySelector('h1').innerHTML = this.value
};
<select id="cars">
<option>Volvo</option>
<option>Saab</option>
<option>Opel</option>
<option>Audi</option>
</select>
<h1><h1>
Upvotes: 0
Reputation: 10094
In the onchange
function, you can simply refer to the select box's value; by default, if there's no value attribute on the option, it'll default to using the option's text.
document.querySelector('#cars').onchange = function() {
document.querySelector('h1').innerHTML = this.value;
};
<select id="cars">
<option>Saab</option>
<option>Honda</option>
<option>Volkswagen</option>
</select>
<h1 id="result"></h1>
Upvotes: 1