2016-11-12 109 views
0
function myfun() { 
    var x = document.getElementById('state').selectedIndex; 
    var text = document.getElementsByTagName("option")[x].value; 
    document.getElementById("pr").innerHTML = text; 
} 

在此代碼document.getElementsByTagName("option")[x].value是取在下拉列表中document.getElementById("pr").innerHTML = text打印在標籤<div id="pr">該值的。但是,價值並不是印刷品。爲什麼?如何打印選定的項目下拉列表中HTHML

+1

哪裏是'HTML'代碼? –

+0

<選擇ID = 「狀態」 的onchange = 「myfun()」><選項值= 「喜」>喜<選項值= 「你好」>你好 –

+0

@MaulikKanani請**添加問題相關的代碼** 。 – Rajesh

回答

0

嘗試這樣的:與應用的text代替valueexample

function myfun() { 
 
    var x = document.getElementById('state').selectedIndex; 
 
    var text = document.getElementsByTagName("option")[x].text;//its a text 
 
    document.getElementById("pr").innerHTML = text; 
 
} 
 
myfun();
<select id="state" onchange="myfun()"> 
 
    <option value="hi">hi</option> 
 
    <option value="hello">hello</option> 
 
</select> 
 
<p id="pr"></p>

備用

function myfun() { 
var x = document.getElementById('state').value; 
    document.getElementById("pr").innerHTML = x 
} 
+0

但對我來說這段代碼無法正常工作什麼都不會打印 –

+0

看到的片段回答其working.change的'text'代替'value'並在onchange事件適用 – prasanth

+0

是的,我會改變的價值,但沒有給定輸出 –

0

function myfun() { 
 
    var x = document.getElementById('state').selectedIndex; 
 
    var text = document.getElementsByTagName("option")[x].text;//its a text 
 
    document.getElementById("pr").innerHTML = text; 
 
} 
 
myfun();
<select id="state" onchange="myfun()"> 
 
    <option value="hi">hi</option> 
 
    <option value="hello">hello</option> 
 
</select> 
 
<p id="pr"></p>

相關問題