Issue
I'd like to show the content of the selected options in the span tags with corresponding id's.
So when you choose Chocolate as your ice cream flavor and Caramel as your topping, the text at the bottom will change to:
"I love Chocolate ice cream with Caramel".
<ul id="icecream" style="list-style:none;line-height:30px;">
<li>
<select id="icecream">
<option value="vanilla">Vanilla</option>
<option value="chocolate">Chocolate</option>
<option value="strawberry">Strawberry</option>
</select>
</li>
<li>
<select id="topping">
<option value="sprinkles">Sprinkles</option>
<option value="chocolatedip">Chocolate Dip</option>
<option value="caramel">Caramel</option>
</select>
</li>
<li>I love <span id="icecreamFlavor"></span> ice cream with <span id="toppingFlavor"></span>.</li>
</ul>
Does anyone know of a javascript that can do this?
Update:
- Without using jQuery.
- Vanilla, Chocolate, Strawberry, Sprinkles, Chocolate Dip, and Caramel don't have to be displayed in bold.
- The first option in the select list is shown as default. I.e.:
"I love Vanilla ice cream with Sprinkles".
Solution
Here's one way:
<!doctype html>
<html>
<head>
<script>
// wait for DOM content to finish loading
window.addEventListener( 'DOMContentLoaded', function DOMContentLoaded() {
// no need to listen anymore
this.removeEventListener( 'DOMContentLoaded', DOMContentLoaded );
// get the DOM elements
var icecream = document.getElementById( 'icecream' );
var topping = document.getElementById( 'topping' );
var icecreamFlavor = document.getElementById( 'icecreamFlavor' );
var toppingFlavor = document.getElementById( 'toppingFlavor' );
// define an event listener that changes our output based on the selected options
var onSelectChange = function( event ) {
icecreamFlavor.textContent = icecream.options[ icecream.selectedIndex ].textContent;
toppingFlavor.textContent = topping.options[ topping.selectedIndex ].textContent;
}
// listen for the change events with the event listener
icecream.addEventListener( 'change', onSelectChange );
topping.addEventListener( 'change', onSelectChange );
// initialize our output
onSelectChange();
} );
</script>
</head>
<body>
<ul style="list-style:none;line-height:30px;">
<li>
<select id="icecream">
<option value="vanilla">Vanilla</option>
<option value="chocolate">Chocolate</option>
<option value="strawberry">Strawberry</option>
</select>
</li>
<li>
<select id="topping">
<option value="sprinkles">Sprinkles</option>
<option value="chocolatedip">Chocolate Dip</option>
<option value="caramel">Caramel</option>
</select>
</li>
<li>I love <span id="icecreamFlavor"></span> ice cream with <span id="toppingFlavor"></span>.</li>
</ul>
</body>
</html>
P.S.: Your <ul>
had a conflicting id
(icecream
), so I had to remove it.
Answered By - Decent Dabbler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.