2016-11-17 128 views
-3

我做了一个脚本来显示视频,如果复选框被选中。document.getElementById(“x”)。checked返回undefined

HTML:

<p class="subParHeader" style="">Video or not</p> 
<form action="#" method="post" style="font-family: Arial;"> 
<input type="checkbox" title="Click here if you want to input a video" value="" id="FormVidOrNot"><input id="FormVidOrNotInput" value="" style="width: 30%"></input></input> 
</form> 

的Javascript:

if(document.getElementById("FormVidOrNot").checked){ 

    document.write('<div class="div_video">'); 
    document.write(JSFormVidOrNotInput); 
    document.write('</div>'); 

} 

但每次我运行它返回未定义的代码的时候,尽管它已经完全在这里运行:

if(document.getElementById("FormVidOrNot").checked){ 
    var JSFormVidOrNotInput = document.getElementById("FormVidOrNotInput").value; 
} 

(这部分是在代码中比第一个脚本更高)

+0

'input'内'input'输入的标签是不合法的HTML。另外'id'必须是唯一的 – brk

+0

user2181397它就是我在代码的另一部分完成的,它的工作原理非常完美,并且所使用的id仅在HTML中使用一次 –

+0

正如user2181397所述,唯一标识符。 – yashpandey

回答

0

试试这个

<p class="subParHeader" style="">Video or not</p> 
    <form action="#" method="post" style="font-family: Arial;"> 
    <input type="checkbox" title="Click here if you want to input a video" value="Test" id="FormVidOrNot"> 
    <input id="FormVidOrNotInput" value="" style="width: 30"> 
    </form> 

请注意,我们没有必要密切

document.getElementById("FormVidOrNot").addEventListener('click',function(){ 
    if(document.getElementById("FormVidOrNot").checked){ 
     var JSFormVidOrNotInput = document.getElementById("FormVidOrNotInput").value; 

     document.write('<div class="div_video">'); 
     document.write(JSFormVidOrNotInput); 
     document.write('</div>'); 
    } 

}); 
+0

感谢您的答案,但它仍然无法正常工作。 –