簡體   English   中英

訪問多個表單選項

[英]Accessing several form options

如何使用JavaScript在一個表單中的兩個不同的選擇ID下訪問幾個選項值?

這是代碼:(JSFiddle: http : //jsfiddle.net/sebastianonline/9yL4rv6j/

(HTML5)

選擇您喜歡的水果:

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

單擊按鈕以返回所選水果的值。

選擇一個產品數量

        <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;

}

函數mySelect()能夠選擇正確的選項值並將其插入第一段中,但是,第二個函數(myAmount())會選擇與第一個函數相同的選項,即使其id指向select id =“量”。 我需要第二個功能來選擇select id =“ amount”中的選項並將其打印在p id =“ include2”中。

您正在使用document.getElementsByTagName("option") ,它返回文檔中的所有選項元素而不是當前select的所有選項。 當然,這意味着您的索引已被刪除。

但是,您可以使用select元素本身的.value屬性在給定的select元素中獲取所選選項的值:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM