【问题标题】:Javascript Alert Box with Radio Button带有单选按钮的 Javascript 警报框
【发布时间】:2014-05-10 15:42:17
【问题描述】:

我是 Javascript 的初学者,我有一个问题要问 - 当没有选择单选按钮时,如何让提交按钮显示一个警告框?我已经尝试了很多次,但似乎没有任何效果 - 任何帮助将不胜感激。谢谢。

<html>
<head>
<title> Reviewer </title>
<style type="text/css">
body
{
background-image: url("reviewerbackground.jpg");
background-attachment: fixed;
font-family: verdana;
color:white;
text-shadow: black 0.1em 0.1em 0.2em;
line-height: 1.5;
font-size: 100%;
}
h1
{
color: white;
font-family: verdana;
text-shadow: black 0.1em 0.1em 0.2em;
text-align: center;
line-height: 1.5;
}
p
{
border: none;
width: 90%;
line-height: 1.5;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
-moz-box-shadow: 0 0 5px rgba(0,0,0,0.5);
-webkit-box-shadow: 0 0 5px rgba(0,0,0,0.5);
box-shadow: 0 0 5px rgba(0,0,0,0.5);
background: tan;
padding: 3px;
text-align: left;
}
</style>

<script type="text/javascript">
function question1() {
   var option = document.querySelector('input[name = "question1"]:checked').value;
   if (option == 'd') {
      alert("That's the correct answer!");
   } 
   else {
      alert ("Oops! try again!");
   }
   }
</script>
</head>
<body link="white" vlink="white">

<br>
<h1> Reviewer  </h1> </br>

<center> 
<p> 1. (Question- Answer will be D, the 4th radio button)
<br>
<br> 
<input type="radio" name="question1" value="a"> choice a
<br>
<input type="radio" name="question1" value="b"> choice b
<br>
<input type="radio" name="question1" value="c"> choice c
<br>
<input type="radio" name="question1" value="d"> choice d
<br>
<br>
<input class="button" type="button" onclick="question1()" name="question1" value="Submit">
</p> </center>
<br>

</body>
</html>

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    试试这个:

     function question1 () {
    
        var option = getRVBN('question1'); 
    
        //Check if no radio is selected
        if(option==''){
        alert("No radio button is selected");
        return false;
       }                 
    
       if (option == 'd') {
          alert("That's the correct answer!");
       } 
       else {
          alert ("Oops! try again!");
       }
    }
    
    function getRVBN(rName) {
        var radioButtons = document.getElementsByName(rName);
        for (var i = 0; i < radioButtons.length; i++) {
            if (radioButtons[i].checked) return radioButtons[i].value;
        }
        return '';
    }
    

    函数getRVBN()来自这篇帖子Getting the selected radio without using "Id" but "name"

    这里是小提琴: http://jsfiddle.net/T9Lpr/18/

    【讨论】:

      【解决方案2】:

      这里只是一个简单的问题,在函数的第一行,您的 querySelector 映射正确,但 :checked 需要一个空格才能工作。

      像这样:

      var option = document.querySelector('input[name = "question1"] :checked').value;    
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-26
        • 1970-01-01
        • 2018-08-15
        • 2011-01-04
        • 2014-09-10
        • 2021-10-23
        • 1970-01-01
        • 2017-02-06
        相关资源
        最近更新 更多