Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  30] [ 6]  / answers: 1 / hits: 33939  / 11 Years ago, mon, august 5, 2013, 12:00:00

How can i get the value of the <select> markup in my html and pass it on my javascript.



when i select red it should display my <div id=red>
im new to JS, so im not sure if i got the correct syntax.



HTML



<select>
<option name=choice1 value=red onclick=color(this.value)>red</option>
<option name=choice2 value=blue onclick=color(this.value)>blue</option>
</select>

<div id=red style=display:none;>
<p>You want RED</p>
</div>

<div id=blue style=display:none;>
<p>You want BLUE</p>
</div>


JAVASCRIPT



function color(color_type){
if (color_type == 'blue'){
document.getElementById('blue').style.display = 'block';
document.getElementById('red').style.display = 'none';
}
else{
document.getElementById('blue').style.display = 'none';
document.getElementById('red').style.display = 'block';
}
}

More From » html

 Answers
60

You should use onchange event instead of onclick, besides, the event should set to select instead of option following is correct code



<script>
function color(color_type){
if (color_type == 'blue'){
document.getElementById('blue').style.display = 'block';
document.getElementById('red').style.display = 'none';
}
else{
document.getElementById('blue').style.display = 'none';
document.getElementById('red').style.display = 'block';
}
}
</script>

<select onchange=color(this.value)>
<option name=choice1 value=red >red</option>
<option name=choice2 value=blue >blue</option>
</select>

<div id=red style=display:none;>
<p>You want RED</p>
</div>

<div id=blue style=display:none;>
<p>You want BLUE</p>
</div>


Hope Helps!


[#76524] Friday, August 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
griffinr

Total Points: 242
Total Questions: 91
Total Answers: 105

Location: Indonesia
Member since Wed, Jul 7, 2021
3 Years ago
;