Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialdon bencilao
4,153 Pointshow to know select option value
hi,
I'm just practicing javascript, and I wanted to build a sort of quoting form.
first the user will pick from the two options, then if the option is selected I want the formula to reference only the objects for that options.
<div class="container">
<p>Type in the requested values</p>
<select id="terminate">
<option>choose</option>
<option value="termite">termite</option>
<option value="rat">rat</option>
</select>
<input id="area" type="text" value="" placeholder="floor area/sq.m">
<button id="calculate">button</button>
<input id="quote" type="text" value="">
</div>
<script>
var x = document.getElementById("terminate").selectedIndex;
var y = document.getElementsByTagName("option")[x].value;
console.log(y);
y.addEventListener('change', function(){
///put code in here///
});
<script>
5 Answers
Jason Anello
Courses Plus Student 94,610 PointsHi Don,
You want to listen for the change event on the select element. Once you select an option, it's the select element that holds the value of what option was selected.
See if this helps you:
var terminate = document.getElementById("terminate");
terminate.addEventListener('change', function(){
console.log(this.value);
});
Coco Jackowski
12,914 PointsYou're looking for JavaScript's .value
as in: var terminateValue = document.getElementById('terminate').value
don bencilao
4,153 Pointsyes of the selected one. can you show me how?
Coco Jackowski
12,914 PointsI'm not sure what you're looking for, other than how to use JavaScript to read the value of a <select>
element, which you do with the code in my previous response. If you place that code inside the anonymous function in your eventListener, the variable terminateValue
will contain the value of the selected input field, and you can use that value to make decisions as to what do do later in the code.
don bencilao
4,153 Pointsyes but what if I pick a different item?
I want the script to change value according to the item selected by the user.