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 trial

JavaScript

how 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

Hi 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
Coco Jackowski
12,914 Points

You're looking for JavaScript's .value as in: var terminateValue = document.getElementById('terminate').value

yes of the selected one. can you show me how?

Coco Jackowski
Coco Jackowski
12,914 Points

I'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.

yes but what if I pick a different item?

I want the script to change value according to the item selected by the user.