2016-11-12 96 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>