简体   繁体   中英

Accessing several form options

How do I access several option values in a form, under two different select ids, with JavaScript?

Here's the code: (JSFiddle: http://jsfiddle.net/sebastianonline/9yL4rv6j/ )

(HTML5)

Select your favorite fruit:

<select id="mySelect">
    <option value="apple">Apple</option>
    <option value="orange">Orange</option>
    <option value="pineapple">Pineapple</option>
    <option value="banana">Banana</option>
</select>

Click the button to return the value of the selected fruit.

Pick a product Amount

        <label><strong>Amount:</strong></label>

        <select id="amount">
            <option selected>1</option>
            <option>2</option>
            <option>3</option>
        </select>

<!-- text value here -->
<p id="include"></p>
<p id="include2"></p>

(JavaScript)

    function mySelect()

{

    var x = document.getElementById("mySelect").selectedIndex;
    var p = document.getElementsByTagName("option")[x].value;
    document.getElementById("include").innerHTML = p;

}

    function myAmount()

{

    var a = document.getElementById("amount").selectedIndex;
    var b = document.getElementsByTagName("option")[a].value;
    document.getElementById("include2").innerHTML = b;

}

Function mySelect() is able to pick the right option value and insert it in the first paragraph, however, the second function (myAmount()) is picking the same options as the first function, even though its id points to select id="amount". I need the second function to pick the options in select id="amount" and print it in p id="include2".

You are using document.getElementsByTagName("option") , which returns all option elements in the document, not all options for the current select. Which of course means your indexing is out.

But you can get the selected option's value in a given select element using the .value property of the select element itself:

function mySelect() {
  var x = document.getElementById("mySelect").value;
  document.getElementById("include").innerHTML = x;
}
function myAmount() {
  document.getElementById("include2").innerHTML =
                                        document.getElementById("amount").value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM