2014-10-05 67 views
0

如何在JavaScript中使用两种不同的select 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指向选择id =“amount”。我需要第二个函数来选择select id =“amount”中的选项并将其打印在p id =“include2”中。

回答

0

您正在使用document.getElementsByTagName("option"),它返回文档中的所有选项元素,不是当前选择的所有选项。这当然意味着你的索引已经不存在了。

但是你可以使用select元素本身的特性.value在给定的选择元素得到了选择的选项的值:

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

这工作得更好,谢谢。 – 2014-10-05 23:50:38