2016-11-17 129 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

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