in an attempt to make practical use of the skills I am learning on my web development course I am trying to create a website about the Vikings for my partner's Primary school class.
I have managed to get the HTML and CSS as I want it, but I'm struggling a little with the Javascript. it all looks fine to my mind but doesn't run as intended.
I have a quiz and a submit button. When clicked this button will reference a "checkresults" function in my .js file.
This should then calculate a result between 0 - 3 and post this result into the HTML page. I have designed the box the results will show in to be invisible until the "Submit" button is clicked. However, when ran the results box appears for only a second before disappearing and I cannot figure out why.
any help or advice would be very much appreciated!
//JAVASCRIPT//
function checkresults() {
var question1 = document.quiz.question1.value;
var question2 = document.quiz.question2.value;
var question3 = document.quiz.question3.value;
var correct = 0;
if (question1 == "793") {
correct++;
}
if (question2 == "Shield") {
correct++;
}
if (question3 == "1066") {
correct++;
}
var message = ["You're a real Viking!", "Not bad but you can do better!",
"Odin would not be pleased with your effort!"];
var range;
if (correct < 1) {
range = 2;
}
if (correct > 0 && correct < 3) {
range = 1;
}
if (correct > 2) {
range = 0;
}
document.getElementById("afterSubmit").style.visibility = "visible"
document.getElementById("message").innerHTML = message[ramge];
document.getElementById("correct").innerHTML = "You got " + correct + "
correct!";
}
//HTML//
<form id="quiz" name="quiz">
<p>When did the Vikings first invade Britain?</p>
<input type="radio" id="mc" name="question1" value="1066" />1066<br />
<input type="radio" id="mc" name="question1" value="793" />793<br />
<input type="radio" id="mc" name="question1" value="411" />411<br />
<input type="radio" id="mc" name="question1" value="1999" />1999<br />
<p>what did every man need before he was allowed to go Viking?</p>
<input type="radio" id="mc" name="question2" value="Shield" />Shield<br />
<input type="radio" id="mc"name="question2" value="Sword" />Sword<br />
<input type="radio" id="mc"name="question2" value="Cloak" />Cloak<br />
<input type="radio" id="mc" name-"question2" value="Gold" />Gold<br />
<p>when did the Viking age end?</p>
<input type="radio" id="mc" name="question3" value="793" />793<br />
<input type="radio" id="mc" name="question3" value="1999" />1999<br />
<input type="radio" id="mc" name="question3" value="1066" />1066<br />
<input type="radio" id="mc" name="question3" value="1500" />1500<br />
<input type="submit" id="button" value="Lets see how you did!" onclick =
"checkresults();">
</form>
<div id="afterSubmit">
<p id="message"></p>
<p id="correct"></p>
//CSS//
#afterSubmit {
visibility: hidden;
border-color: red;
border-style: solid;
border-width: 5px;
}
Your page is refreshing.
The best way to change this would be to move the function to the form onsubmit event.
//Remove the onclick
<input type="submit" id="button" value="Lets see how you did!" onclick="checkresults();">
Add the function and return false to the event on the form, so it cancels submission
//Add the onsubmit, notice the return false, so it cancels submission
<form id="quiz" name="quiz" onsubmit="checkresults();return false;">
Related
I'm playing around with a javascript quiz but I'm having trouble showing the results. I would like the user to see the correct results when the user clicks on "Submit Answers" but nothing happens.
This is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title> Simple JavaScript Quiz </title>
<link rel="stylesheet" href="css/style.css">
<script src="js/script.js"> </script>
</head>
<body>
<div id="container">
<header>
<h1> Simple JavaScript Quiz</h1>
<p> Test your knowledge in <strong>JavaScript fundamentals</strong></p>
</header>
<section>
<div id="results"> </div>
<form name="quizForm" onsubmit="return submitAnswers()">
<h3>1. In which elements do we put in JavaScript code?</h3>
<img src="scam.png" alt="Italian Trulli">
<input type="radio" name="q1" value="a" id="q1a">a. <js><br>
<input type="radio" name="q1" value="b" id="q1b">b. <script><br>
<input type="radio" name="q1" value="c" id="q1c">c. <body><br>
<input type="radio" name="q1" value="d" id="q1d">d. <link><br>
<h3>2. Which HTML attribute is used to reference an external JavaScript file?</h3>
<input type="radio" name="q2" value="a" id="q2a">a. src<br>
<input type="radio" name="q2" value="b" id="q2b">b. rel<br>
<input type="radio" name="q2" value="c" id="q2c">c. type<br>
<input type="radio" name="q2" value="d" id="q2d">d. href<br>
<h3>3. How would you write "Hello" in an alert box?</h3>
<input type="radio" name="q3" value="a" id="q3a">a. msg("Hello");<br>
<input type="radio" name="q3" value="b" id="q3b">b. alertBox("Hello");<br>
<input type="radio" name="q3" value="c" id="q3c">c. document.write("Hello");<br>
<input type="radio" name="q3" value="d" id="q3d">d. alert("Hello");<br>
<input type="submit" value="Submit Answers"> <br><br>
</form>
</section>
</div>
</body>
</html>
And this is my javascript code:
function submitAnswers() {
var total = 3;
var score = 0;
// get user input
var q1 = document.forms["quizForm"]["q1"].value;
var q2 = document.forms["quizForm"]["q2"].value;
var q3 = document.forms["quizForm"]["q3"].value;
// set correct answers
var answers = ['b', 'a', 'd'];
// check answers (note i - 1 to account for array starting with [0])
for (var i = 1; i <= total; i++) {
if (eval("q" + i) == answers[i - 1]) {
score++;
}
}
// display results
var results = document.getElementById("results");
results.innerHTML ='<h3>You Scored <span> '+score+' </span> out of <span>'+total+'</span> </h3>';
alert('You Scored '+score+' out of '+total);
}
After I click "Submit Answers" nothing happens. Any ideas?
Instead of adding onsubmit property directly in form element, add submit event listener on it and prevent the event from default behavior. Default behavior of submitig a form is refreshing whole page.
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
submitAnswers();
})
I'm building a very simple quiz and I've hit a small wall. So my structure is that I've made 5 questions (using radio buttons) giving the correct radio button an ID, and then in JavaScript I'd target those radio buttons. But the answers I'd store in a array. I've tested it out on the first question to see if the array index would work in my if statement but it does not. For example: if(radio1.checked === answers[0]) then it should alert saying that its correct. But instead it does my else statement, not sure how I could go by doing this, any suggestions?
SIDE NOTE: I'm new to JavaScript so I want to learn how to use arrays properly
var score = 0;
var radio1 = document.getElementById('correctradio1');
var submit = document.getElementById('submit');
submit.addEventListener('click', function quiz(){
var answers = ['Yellow', 'Donald trump', 'Michael Jackson', 'red', 'Oscar'];
if(radio1.checked === answers[0]) {
document.getElementById('results').innerHTML = "yes thats correct";
}else{
alert('nope');
}
});
<h2>
Knowlegde Quiz
</h2>
<br>
<p>What is the color of the sun?</p>
<input type="radio" name="selection" id="correctradio1"> Yellow<br>
<input type="radio" name="selection" > Green<br>
<input type="radio" name="selection" > Blue
<p>Who is the President?</p>
<input type="radio" name="selection" id="correctradio2"> Donald trump<br>
<input type="radio" name="selection"> Beyonce<br>
<input type="radio" name="selection"> Blue Ivy
<p>Who was the lead singer in The Jackson 5?</p>
<input type="radio" name="selection"> Marvin gaye<br>
<input type="radio" name="selection"> Toni braxton<br>
<input type="radio" name="selection" id="correctradio3"> Michael Jackson
<p>What color is Elmo?</p>
<input type="radio" name="selection"> Green<br>
<input type="radio" name="selection"> pink<br>
<input type="radio" name="selection" id="correctradio4"> red
<p>Who created the Muppets?</p>
<input type="radio" name="selection"> Elmo<br>
<input type="radio" name="selection" id="correctradio5"> Jim Henson<br>
<input type="radio" name="selection"> Oscar<br><br>
<input type="submit" value="Submit Quiz" id="submit">
<h3>You got <span id="results"></span> correct
</h3>
Radio buttons need to have a value set for them so that it has meaning when you select one. That value is what you want to compare against your array values. Your code tries to compare the true/false value of the checked property against the answers in your array, which will always result in an incorrect answer because true (the value of the checked property on the checked radio button) is not one of the correct answers.
Next, if you always compare the value of the "correct answer" radio button against the correct answers, you'll never get a wrong answer. When the submit button is pressed, you need to look for which button (from each group) was checked and compare each value against the corresponding correct answer in the array.
Additionally, each group of radio buttons must have a name that is different from the other groups, so that each group can have one choice selected. Right now, in your code, you can only select one radio button from all the choices.
var score = 0;
var submit = document.getElementById('submit');
var result = document.getElementById('results')
var answers = ['Yellow', 'Donald Trump', 'Michael Jackson', 'red', 'Oscar'];
submit.addEventListener('click', function quiz(){
// You need to get the checked radio button at the time that the submit button is pressed.
var checkedRadioButton1 = document.querySelector("input[name='selection1']:checked");
// Compare the *value* of the radio button against the value in the array.
if(checkedRadioButton1.value == answers[0]) {
result.textContent = "yes thats correct";
}else{
alert('nope');
}
});
<h2>
Knowlegde Quiz
</h2>
<p>What is the color of the sun?</p>
<input type="radio" name="selection1" id="correctradio1" value="Yellow"> Yellow<br>
<input type="radio" name="selection1" value="Green"> Green<br>
<input type="radio" name="selection1" value="Blue"> Blue
<p>Who is the President?</p>
<input type="radio" name="selection2" id="correctradio2" value="Donald trump"> Donald Trump<br>
<input type="radio" name="selection2" value="Beyonce"> Beyonce<br>
<input type="radio" name="selection2" value="Blue Ivy"> Blue Ivy
<p>Who was the lead singer in The Jackson 5?</p>
<input type="radio" name="selection3" value="Marvin Gaye"> Marvin gaye<br>
<input type="radio" name="selection3" value="Toni Braxton"> Toni braxton<br>
<input type="radio" name="selection3" value="Michael Jackson" id="correctradio3"> Michael Jackson
<p>What color is Elmo?</p>
<input type="radio" name="selection4" value="green"> Green<br>
<input type="radio" name="selection4" value="pink"> pink<br>
<input type="radio" name="selection4" value="red" id="correctradio4"> red
<p>Who created the Muppets?</p>
<input type="radio" name="selection5" value="Elmo"> Elmo<br>
<input type="radio" name="selection5" value="Jim Henson" id="correctradio5"> Jim Henson<br>
<input type="radio" name="selection5" value="Oscar"> Oscar<br><br>
<input type="submit" value="Submit Quiz" id="submit">
<h3>You got <span id="results"></span> correct
</h3>
While this is a good first approach for someone that is new to JavaScript, it really is pretty wasteful in terms of coding. A much more streamlined approach would be as follows (read the comments for explanation):
var score = 0;
var submit = document.getElementById('submit');
var result = document.getElementById('results')
var incorrect = [];
// When comparing strings, remember that case matters. Store all the strings
// as lower case and then later, we'll compare lower case against lower case.
var answers = ['yellow', 'donald trump', 'michael jackson', 'red', 'jim henson'];
submit.addEventListener('click', function(){
// Reset game
incorrect = [];
score = 0;
// Get the checked radio button from each group and place into an array
var checkedByGroup = Array.prototype.slice.call(document.querySelectorAll("input[type='radio']:checked"));
// Count how many checks were made and if the user didn't answer all
// the questions, exit with a message:
if(checkedByGroup.length < answers.length){
alert("You didn't answer all the questions! Try again!");
return;
}
// Now you have two arrays: one with all the correct answers and
// one with radio buttons. Both arrays have the same amount of items
// and each index in each array corresponds to each other.
// Loop through the correct answers:
answers.forEach(function(value, index){
// Compare the answer against the corresponding radio button array
// Remember to compare lower case against lower case!
if(checkedByGroup[index].value.toLowerCase() === value){
score++; // Add a point
} else {
incorrect.push(index + 1); // Add question number to incorrect array
}
});
// If you didn't get a perfect score:
if(score !== 5){
// Tell the player which questions they got wrong
alert("You got question(s) " + incorrect.join() + " wrong!");
}
// Either way, report the score
result.textContent = "You got " + score + " right!";
});
<h2>Knowlegde Quiz</h2>
<p>What is the color of the sun?</p>
<input type="radio" name="q1" value="Yellow"> Yellow<br>
<input type="radio" name="q1" value="Green"> Green<br>
<input type="radio" name="q1" value="Blue"> Blue
<p>Who is the President?</p>
<input type="radio" name="q2" value="Donald trump"> Donald Trump<br>
<input type="radio" name="q2" value="Beyonce"> Beyonce<br>
<input type="radio" name="q2" value="Blue Ivy"> Blue Ivy
<p>Who was the lead singer in The Jackson 5?</p>
<input type="radio" name="q3" value="Marvin Gaye"> Marvin gaye<br>
<input type="radio" name="q3" value="Toni Braxton"> Toni braxton<br>
<input type="radio" name="q3" value="Michael Jackson"> Michael Jackson
<p>What color is Elmo?</p>
<input type="radio" name="q4" value="green"> Green<br>
<input type="radio" name="q4" value="pink"> pink<br>
<input type="radio" name="q4" value="red"> red
<p>Who created the Muppets?</p>
<input type="radio" name="q5" value="Elmo"> Elmo<br>
<input type="radio" name="q5" value="Jim Henson"> Jim Henson<br>
<input type="radio" name="q5" value="Oscar"> Oscar<br><br>
<input type="submit" value="Submit Quiz" id="submit">
<h3 id="results"></h3>
Radio button need to have value and instead of using getElementById use querySelector. like below.
var score = 0;
var submit = document.getElementById('submit');
submit.addEventListener('click', function quiz(){
var radio1 = document.querySelector('input[name="selection"]:checked').value;
var answers = ['Yellow', 'Donald trump', 'Michael Jackson', 'red', 'Oscar'];
console.log(radio1);
if(radio1 === answers[0]) {
document.getElementById('results').innerHTML = "yes thats correct";
}else{
alert('nope');
}
});
<h2>
Knowlegde Quiz
</h2>
<br>
<p>What is the color of the sun?</p>
<input type="radio" name="selection" id="correctradio1" value="Yellow"> Yellow<br>
<input type="radio" name="selection" value="Green"> Green<br>
<input type="radio" name="selection" value="Blue"> Blue<br>
<input type="submit" value="Submit Quiz" id="submit">
<h3>You got <span id="results"></span> correct
</h3>
You're really close. You actually don't need the array of answers because you've already marked your answers with the class "correctradioX".
You can complete this by just adding each one into the if as I've done below.
var score = 0;
var radio1 = document.getElementById('correctradio1');
var radio2 = document.getElementById('correctradio2');
var radio3 = document.getElementById('correctradio3');
var radio4 = document.getElementById('correctradio4');
var radio5 = document.getElementById('correctradio5');
var submit = document.getElementById('submit');
submit.addEventListener('click', function quiz(){
var answers = ['Yellow', 'Donald trump', 'Michael Jackson', 'red', 'Oscar'];
if (radio1.checked &&
radio2.checked &&
radio3.checked &&
radio4.checked &&
radio5.checked) {
document.getElementById('results').innerHTML = "yes thats correct";
} else {
alert('nope');
}
});
<h2>
Knowlegde Quiz
</h2>
<br>
<p>What is the color of the sun?</p>
<input type="radio" name="q1" id="correctradio1"> Yellow<br>
<input type="radio" name="q1" > Green<br>
<input type="radio" name="q1" > Blue
<p>Who is the President?</p>
<input type="radio" name="q2" id="correctradio2"> Donald trump<br>
<input type="radio" name="q2"> Beyonce<br>
<input type="radio" name="q2"> Blue Ivy
<p>Who was the lead singer in The Jackson 5?</p>
<input type="radio" name="q3"> Marvin gaye<br>
<input type="radio" name="q3"> Toni braxton<br>
<input type="radio" name="q3" id="correctradio3"> Michael Jackson
<p>What color is Elmo?</p>
<input type="radio" name="q4"> Green<br>
<input type="radio" name="q4"> pink<br>
<input type="radio" name="q4" id="correctradio4"> red
<p>Who created the Muppets?</p>
<input type="radio" name="q5"> Elmo<br>
<input type="radio" name="q5" id="correctradio5"> Jim Henson<br>
<input type="radio" name="q5"> Oscar<br><br>
<input type="submit" value="Submit Quiz" id="submit">
<h3>You got <span id="results"></span> correct</h3>
i'm new to Javascript and Jquery and i am trying to create a kind of questionnaire style page.
Essentially i want to ask a question, then once i have chosen an answer make everything in smaller and then display the next question in normal size.
I have most of the page working in terms of showing and hiding but i cant seem to get the code to work when i try to make the initial question text smaller.
Ive read lots of tutorials and examples but none seem to work, i'd really appreciate any guidance.
Thanks in advance !
Here is my HTML
<form>
<fieldset class="form1">
<p>what problem is the customer having ?</p>
<input type="radio" name="issue" value="o - issue1" onClick="getIssueVar()">issue1<br/>
<input type="radio" name="issue" value="o - issue2" onClick="getIssueVar()">issue2<br/>
<input type="radio" name="issue" value="o - issue3" onClick="getIssueVar()">issue3<br/>
<input type="radio" name="issue" value="o - issue4" onClick="getIssueVar()">issue4<br/>
</fieldset>
</form>
<br/>
Here is my Javascript:
function getIssueVar() {
var xissue = document.getElementById("testform");
var issuetext = "";
var iissue;
for (iissue = 0; iissue < xissue.length ;iissue++) {
if (xissue[iissue].checked) {
issuetext=xissue[iissue].value;
break;
}
}
document.getElementById("faultissue").innerHTML = issuetext;
$(".form2").show();
$(".form1").css('font-size', '10px');
}
I have set my css:
.form1
{
font-size:14px;
}
so i was thinking i would use javascript/jquery to change the font size once ive clicked on the radio buttons.
What am i doing wrong ?
HTML
<form>
<fieldset class="form1">
<p>what problem is the customer having ?</p>
<input type="radio" name="issue" value="o - issue1" onClick="getIssueVar()" class="testform">issue1<br/>
<input type="radio" name="issue" value="o - issue2" onClick="getIssueVar()" class="testform">issue2<br/>
<input type="radio" name="issue" value="o - issue3" onClick="getIssueVar()" class="testform">issue3<br/>
<input type="radio" name="issue" value="o - issue4" onClick="getIssueVar()" class="testform">issue4<br/>
</fieldset>
</form>
<div id="faultissue"></div>
SCRIPT
function getIssueVar() {
debugger
var xissue = document.getElementsByClassName("testform");
var issuetext = "";
var iissue;
for (iissue = 0; iissue < xissue.length ;iissue++) {
if (xissue[iissue].checked) {
issuetext=xissue[iissue].value;
break;
}
}
document.getElementById("faultissue").innerHTML = issuetext;
$(".form2").show();
$(".form1").css('font-size', '10px');
}
DEMO
From your code it seems testform class is missing from radio button tag. And an element having id faultissue is missing too.
Here is a jQuery solution using a delegated on() click approach.
<form>
<fieldset class="form1">
<p>what problem is the customer having ?</p>
<input type="radio" name="issue" value="o - issue1" >issue1
<br>
<input type="radio" name="issue" value="o - issue2" >issue2
<br>
<input type="radio" name="issue" value="o - issue3" >issue3
<br>
<input type="radio" name="issue" value="o - issue4" >issue4
</fieldset>
</form>
.minimize {
font-size: 0.5em;
}
$('fieldset').on('click', 'input[type="radio"]', function() {
$radio = $(this);
$fieldset = $radio.parent();
$fieldset.addClass('minimize');
});
jsFiddle: http://jsfiddle.net/w4L1g2dc/
I added a class but you could set the CSS directly if you wanted.
Note: I am just learning javascript. So please no jQuery answers yet. I'll get there.
I have 7 forms, all with groups of radio buttons, that appear one-by-one as one button of each form is clicked. Works fine. But by the time I'm done, I may have dozens of forms. There has to be a better way to get the value of a clicked button that creating a getValue for each form. Here's what I've done that works:
<script>
function initdisplay() {
document.getElementById("painLocation").style.display="block";
document.getElementById("painSystem").style.display="none";
document.getElementById("painTemporPatt").style.display="none";
document.getElementById("painIntensDur").style.display="none";
document.getElementById("painEtiology").style.display="none";
document.getElementById("painKav").style.display="none";
}
window.onload = initdisplay;
var painLocationValue = 0;
var painSystemValue = 0;
var painTemporPattValue = 0;
var painIntesDurValue = 0;
var painEtiologyValue = 0;
var painKavValue = 0;
function getPainLocationValue() {
var radioButtons = document.getElementsByName("location");
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
painLocationValue = radioButtons[i].value;
document.getElementById("painLocation").style.display="none";
document.getElementById("painSystem").style.display="block";
alert(painLocationValue);
}
}
}
// ... other similar methods here
function getPainKavValue() {
var radioButtons = document.getElementsByName("kav");
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
painKavValue = radioButtons[i].value;
document.getElementById("painKav").style.display="none";
alert(radioButtons[i].value);
}
}
}
</script>
</head>
Then the HTML looks like this:
<body>
<form id="painLocation" action="">
<p class="formPainCode">Q1: What is the location of your ailment?</p>
<input type="radio" name="location" value="000" onclick="getPainLocationValue()"> Head, Face, Mouth<br><br>
<input type="radio" name="location" value="100" onclick="getPainLocationValue()"> Cervical (neck) Region<br><br>
<input type="radio" name="location" value="200" onclick="getPainLocationValue()"> Upper Shoulder and Upper Limbs<br><br>
<input type="radio" name="location" value="300" onclick="getPainLocationValue()"> Thoracic (chest) Region<br><br>
<input type="radio" name="location" value="400" onclick="getPainLocationValue()"> Abdominal Region<br><br>
<input type="radio" name="location" value="500" onclick="getPainLocationValue()"> Lower Back, Lumbar Spine, Sacrum, Coccyx<br><br>
<input type="radio" name="location" value="600" onclick="getPainLocationValue()"> Lower Limbs<br><br>
<input type="radio" name="location" value="700" onclick="getPainLocationValue()"> Pelvic Region<br><br>
<input type="radio" name="location" value="800" onclick="getPainLocationValue()"> Anal, Perineal, Genital Region<br><br>
<input type="radio" name="location" value="900" onclick="getPainLocationValue()"> More than one location<br><br>
</form>
...
<form id="painKav" action="">
<p class="formPainCode">Q11: On which side of your body is your ailment?</p>
<input type="radio" name="kav" value="R" onclick="getPainKavValue()"> Right<br><br>
<input type="radio" name="kav" value="L" onclick="getPainKavValue()"> Left<br><br>
<input type="radio" name="kav" value="C" onclick="getPainKavValue()"> Center<br><br>
<input type="radio" name="kav" value="M" onclick="getPainKavValue()"> More than one side<br><br>
</form>
</body>
</html>
After another couple of frustrating hours, I dropped my "no jQuery" condition. The rest was simple. I used the following code to detect a click, and get the value of the button clicked. And since I expected some of my forms to include input types other than radio buttons, I changed that as well. At this point, the jQuery looks like this:
<script>
$(document).ready(function () {
$("input").click(function() {
var painCode = $(this).val();
alert("The painCode for this person is " + painCode);
});//end click function
}); //end document ready
</script>
I cleaned up the html. A typical form now looks like this:
<div id="painIntensDur">
<form class="painCodeForm" action="">
<p class="formPainCode">Q4: If you experience pain from your ailment, which of the following best describes its intensity and duration? </p>
<input type="radio" name="intensdur" value=".1" > Mild and less than 1 month<br><br>
<input type="radio" name="intensdur" value=".8" > Mild and 1 to 6 months<br><br>
<input type="radio" name="intensdur" value=".9" > Mild and more than 6 months<br><br>
<input type="radio" name="intensdur" value=".4" > Medium and less than 1 month<br><br>
<input type="radio" name="intensdur" value=".2" > Medium and 1 to 6 months<br><br>
<input type="radio" name="intensdur" value=".3" > Medium and more than 6 months<br><br>
<input type="radio" name="intensdur" value=".7" > Severe and less than 1 month<br><br>
<input type="radio" name="intensdur" value=".5" > Severe and 1 to 6 months<br><br>
<input type="radio" name="intensdur" value=".6" > Severe and more than 6 months<br><br>
<input type="radio" name="intensdur" value=".0" > Not sure<br><br>
</form>
</div>
Thanks again to the excellent advice. I'm sure it will come in handy later.
I have a form with 3 questions that have 3 radio options each. I want the form to send an alert if ANY of the questions are left blank. This code sends an alert only if ALL of the questions are left blank:
if (!$("input").is(':checked')) {
alert("You left one blank!");
}
So, for example, if I have only one question answered, I want the alert to send. Instead, it continues on with the code.
You have 3 radio groups, so there will be 3 checked inputs and 6 unchecked inputs, I suggest:
if ( $("input[type=radio]:checked").length < 3 ) {
alert('Please answer all of the questions');
}
Try this:
$(document).ready(function () {
$("#btn1").on("click", function () {
var count = 0;
var questions = $("div.question");
questions.each(function () {
if ($(this).find("input").filter('[type="radio"]').filter(":checked").length > 0) {
count++;
}
});
if (count >= questions.length) {
alert("all good");
} else {
alert("something not checked");
}
});
});
With the HTML:
<div class="question">
Question 1:
<input type="radio" name="radio1" />
<input type="radio" name="radio1" />
<input type="radio" name="radio1" />
</div>
<div class="question">
Question 2:
<input type="radio" name="radio2" />
<input type="radio" name="radio2" />
<input type="radio" name="radio2" />
</div>
<div class="question">
Question 3:
<input type="radio" name="radio3" />
<input type="radio" name="radio3" />
<input type="radio" name="radio3" />
</div>
<div>
<input type="button" id="btn1" value="Submit" />
</div>
http://jsfiddle.net/4yQHv/1/
You can change if (count >= questions.length) { to be === instead of >= to make sure exactly 1 radio button is chosen for every question. Otherwise, this allows for more than one radio button to be chosen (which isn't exactly possible when they're grouped by name attribute)...but just wanted to point that out.
http://jsfiddle.net/tVUuW/
<form>
<input type="radio" name="facepunch" class="facepunch" value="1" />
<input type="radio" name="facepunch" class="facepunch" value="2" />
<input type="radio" name="facepunch" class="facepunch" value="3" />
<br />
<input type="radio" name="stack" class="stack" value="1" />
<input type="radio" name="stack" class="stack" value="2" />
<input type="radio" name="stack" class="stack" value="3" />
<br />
<input id="button" type="button">
</form>
$(document).ready(function(){
$('#button').click(function(){
if(!$("input.facepunch:checked").val()) {
alert("Please select facepunch");
}
if(!$("input.stack:checked").val()) {
alert("Please select stack");
}
});
});
If you have only few groups of radios you can use this method, this is one way to validate user data.
I recommend you to check out one of the great jQuery Validation Plugins out there:
jzaefferer plugin, bassistance plugin
Also, Make sure you validate it on the server side as well! The user can send request to your server from somewhere else or even disable javascript on his browser
You can loop through all your radio buttons and see if any of them is unchecked:
$('input[type="radio"]').each(function () {
if( ! $(this).is(':checked') ) {
alert('You left one blank!');
return false; //exit function, so alert won't show multiple times
}
});
Example