簡體   English   中英

如何確定是否選中了單選按鈕組中的特定單選按鈕?

[英]How to determine if a specific radio button in a radio button group is checked?

我的HTML表單中有一個單選按鈕組:

<form action="handler.php">
  <p><b>a or b or c</b></p>
  <p><input type="radio" id="abc" name="answer" value="a1">1<Br>
  <input type="radio" id="abc" name="answer" value="a2">2<Br>
  <input type="radio" id="abc" name="answer" value="a3">3</p>
 </form>

我想檢查是否檢查了特定的單選按鈕(例如,值為a1 ),然后顯示是否為圖片:

<script>
function ShowPicture() {
  var word = document.getElementById("abc").value;

  if (word == "a1") {
      document.getElementById("demo").innerHTML = '<iframe src="http://picturesite.com/index" width="1024" height="720" align="left">';
  } 
}
</script>

如何確定是否選中了單選按鈕,以便可以在用於顯示圖像的條件下使用它?

這可以幫助您:

 <html> <head> </head> <body> <form action="handler.php"> <p><b>a or b or c</b></p> <p><input type="radio" class="abc" name="answer" value="a1" onchange="ShowPicture()">1</p> <p><input type="radio" class="abc" name="answer" value="a2" onchange="ShowPicture()">2</p> <p><input type="radio" class="abc" name="answer" value="a3" onchange="ShowPicture()">3</p> </form> <div id="demo"></div> <script> function ShowPicture() { var word = document.getElementsByClassName("abc"); var len = word.length; for(var i=0;i< len-1; i++) { if(word[i].value == "a1" && word[i].checked) document.getElementById("demo").innerHTML = '<iframe src="http://picturesite.com/index" width="1024" height="720" align="left">' } } </script> </body> </html> 

id必須是唯一的,因此您的代碼無法正常工作! 但是我有兩種方法來解決您的問題。第一種是通過名稱獲取,第二種是通過標記名獲取。這兩個函數返回節點列表,因此需要循環...

//var word = document.getElementsByName("answer"); //get by name
 var word = document.getElementsByTagName("input");//get element name
 for(var i =0;i<word.length;i++){
  if(word[i].value == "a1") {
  document.getElementById("demo").innerHTML = '<iframe src="http://picturesite.com/index" width="1024" height="720" align="left">';
  } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM