如何通过id和输出文本获取选项元素

时间:2015-07-20 04:08:34

标签: javascript

有人可以用这个小javascript帮助我。我希望只有在选择了选项值2时才能在NA中显示rersult。我想要11"显示将显示。需要一个简单的脚本来根据值文本输出自定义文本。我知道我有价值=" 2"上市两次。我不能使用值字段。

<select id="sizing-change" onchange="myFunction()">
    <option value="2">12"</option>
    <option value="2" id="test">11"</option>
</select>

<div class="sizefinal">
    Suggested Size: <span id="finalsize">NA</span>
</div>

<script>
function myFunction() {         
    if(document.getElementById("test").value == "11") {
    document.getElementById("finalsize").innerHTML = "Size: 11";
  }
}
</script>

3 个答案:

答案 0 :(得分:2)

您可以查看选项的文字,如

function myFunction() {
  var el = document.getElementById("sizing-change");
  if (el.options[el.selectedIndex].text.trim() == '11"') {
    document.getElementById("finalsize").innerHTML = "Size: 11";
  } else {
    document.getElementById("finalsize").innerHTML = "NA";
  }
}
<select id="sizing-change" onchange="myFunction()">
  <option value="2">12"</option>
  <option value="2" id="test">11"</option>
</select>

<div class="sizefinal">
  Suggested Size: <span id="finalsize">NA</span>
</div>

答案 1 :(得分:2)

如果您可以将选项的value字段更改为不同的值(您应该),那么您可以尝试这样做:

<select id="sizing-change" onchange="myFunction()">
    <option value="12">12</option>
    <option value="11" id="test">11</option>
</select>
<div class="sizefinal">Suggested Size: <span id="finalsize">NA</span>

</div>
<script>
    function myFunction() {
        if (document.getElementById("sizing-change").value == 11) {
            document.getElementById("finalsize").innerHTML = "Size: 11";
        }
    }
</script>

演示:http://jsfiddle.net/GCu2D/784/

答案 2 :(得分:1)

&#13;
&#13;
var finalsize = document.querySelector('#finalsize');
var sizingChange = document.querySelector('#sizing-change')
var testOption = sizingChange.querySelector('#test');

myFunction(sizingChange);

function myFunction(element) {
  var checked = element.querySelector(':checked');
  
   if (checked == testOption) {
       finalsize.innerHTML = "Size: " + element.querySelector(':checked').text;
   } else {
       finalsize.innerHTML = 'NA';
   }
}
&#13;
<select id="sizing-change" onchange="myFunction(this)">
    <option value="2">12"</option>
    <option value="2" id="test">11"</option>
</select>

<div class="sizefinal">
    Suggested Size: <span id="finalsize">NA</span>
</div>
&#13;
&#13;
&#13;