带有单选按钮的Javascript警报框

时间:2014-05-10 15:42:18

标签: javascript html

我是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>

2 个答案:

答案 0 :(得分:2)

试试这个:

 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/

答案 1 :(得分:0)

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

像这样:

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