Multiple Radio button call with jquery issue - javascript

I would like to make a simple quiz that checks for correct answers and counts the score which outputs on the bottom of the page. I was able to do it with simple js and html but would like to do the same using jquery. However when i press submit in jquery version nothing happens ( i am a noob to jquery and cant find what is wrong) Thanks in advance!
//Question One Answer is 'a'
//Question One Answer is 'b'
//Question One Answer is 'b'
//Question One Answer is 'b'
//Question One Answer is 'a'
var score = 0;
checkAll = function() {
var message;
// var score = 0;
if ($("#question1").val() === "a") {
score++;
} else {
return false;
}
if ($("#question2").val() === "b") {
score++;
} else {
return false;
}
if ($("#question3").val() === "b") {
score++;
} else {
return false;
}
if ($("#question4").val() === "b") {
score++;
} else {
return false;
}
if ($("#question5").val() === "a") {
score++;
} else {
return false;
}
message = "You got " + score + "out of five questions right!";
$("#results").html(message);
initialize = function() {
$("#init").click(checkAll)
};
};
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Form Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script type="text/javascript" src="quiz.js"></script>
</head>
<body>
<h1>Geography Quiz</h1>
<p>
<label for="user">Name:</label>
<input type="text" name="username" id="user" />
</p>
<div class="qheader">
<p> 1) Which of the countries below is largest by area?</p>
</div>
<div class="questsel">
<input type="radio" value="a" name="question1">a) Russia<br>
<input type="radio" value="b" name="question1">b) China<br>
<input type="radio" value="c" name="question1">c) USA<br>
<input type="radio" value="d" name="question1">d) Canada<br>
</div>
<br>
<div class="qheader">
<p> 2) Which of these cities is United States Capital?</p>
</div>
<div class="questsel">
<input type="radio" value="a" name="question2">a) New York<br>
<input type="radio" value="b" name="question2">b) Washington D.C
<input type="radio" value="c" name="question2">c) Chicago<br>
<input type="radio" value="d" name="question2">d) Moscow<br>
</div>
<div class="qheader">
<p> 3) Which of these cities is Spain's Capital?</p>
</div>
<div class="questsel">
<input type="radio" value="a" name="question3">a) Barcelona<br>
<input type="radio" value="b" name="question3">b) Madrid <br>
<input type="radio" value="c" name="question3">c) Milan<br>
<input type="radio" value="d" name="question3">d) Rome<br>
</div>
<div class="qheader">
<p> 4) Which ocean is the largest?</p>
</div>
<div class="questsel">
<input type="radio" value="a" name="question4">a) Arctic<br>
<input type="radio" value="b" name="question4">b) Pacific<br>
<input type="radio" value="c" name="question4">c) Indian<br>
<input type="radio" value="d" name="question4">d) Atlantic<br>
</div>
<div class="qheader">
<p> 5) Which of these rivers is largest in North America?</p>
</div>
<div class="questsel">
<input type="radio" value="a" name="question5">a) Missouri River<br>
<input type="radio" value="b" name="question5">b) Nile River <br>
<input type="radio" value="c" name="question5">c) Amazon River<br>
<input type="radio" value="d" name="question5">d) Yenisei River<br>
</div>
<p>
<input type="button" id="init" value="Submit" />
</p>
<p id="results"></p>
</form>
</body>
</html>

First, you have your initialize() function inside the checkAll() function. It should be a separate function.
Second, you never call initialize().
Third, you use $("#question1").val() to get the value of a radio button, but # is for matching IDs, not names. The way to get the value of a radio button is $(":radio[name=question1]:checked").val() (see jQuery get value of selected radio button).
Fourth, you return immediately whenever an answer is wrong. You need to keep going so you can report the total score.
Fifth, you need to initialize score to 0 in the function. Otherwise, you'll add the score for the current call to the score from the previous time. And score should just be a local variable in the function, there's no need for the global variable.
//Question One Answer is 'a'
//Question One Answer is 'b'
//Question One Answer is 'b'
//Question One Answer is 'b'
//Question One Answer is 'a'
checkAll = function() {
var message;
var score = 0;
if ($(":radio[name=question1]:checked").val() === "a") {
score++;
}
if ($(":radio[name=question2]:checked").val() === "b") {
score++;
}
if ($(":radio[name=question3]:checked").val() === "b") {
score++;
}
if ($(":radio[name=question4]:checked").val() === "b") {
score++;
}
if ($(":radio[name=question5]:checked").val() === "a") {
score++;
}
message = "You got " + score + " out of five questions right!";
$("#results").html(message);
};
initialize = function() {
$("#init").click(checkAll)
};
initialize();
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<h1>Geography Quiz</h1>
<p>
<label for="user">Name:</label>
<input type="text" name="username" id="user" />
</p>
<div class="qheader">
<p> 1) Which of the countries below is largest by area?</p>
</div>
<div class="questsel">
<input type="radio" value="a" name="question1">a) Russia<br>
<input type="radio" value="b" name="question1">b) China<br>
<input type="radio" value="c" name="question1">c) USA<br>
<input type="radio" value="d" name="question1">d) Canada<br>
</div>
<br>
<div class="qheader">
<p> 2) Which of these cities is United States Capital?</p>
</div>
<div class="questsel">
<input type="radio" value="a" name="question2">a) New York<br>
<input type="radio" value="b" name="question2">b) Washington D.C
<input type="radio" value="c" name="question2">c) Chicago<br>
<input type="radio" value="d" name="question2">d) Moscow<br>
</div>
<div class="qheader">
<p> 3) Which of these cities is Spain's Capital?</p>
</div>
<div class="questsel">
<input type="radio" value="a" name="question3">a) Barcelona<br>
<input type="radio" value="b" name="question3">b) Madrid <br>
<input type="radio" value="c" name="question3">c) Milan<br>
<input type="radio" value="d" name="question3">d) Rome<br>
</div>
<div class="qheader">
<p> 4) Which ocean is the largest?</p>
</div>
<div class="questsel">
<input type="radio" value="a" name="question4">a) Arctic<br>
<input type="radio" value="b" name="question4">b) Pacific<br>
<input type="radio" value="c" name="question4">c) Indian<br>
<input type="radio" value="d" name="question4">d) Atlantic<br>
</div>
<div class="qheader">
<p> 5) Which of these rivers is largest in North America?</p>
</div>
<div class="questsel">
<input type="radio" value="a" name="question5">a) Missouri River<br>
<input type="radio" value="b" name="question5">b) Nile River <br>
<input type="radio" value="c" name="question5">c) Amazon River<br>
<input type="radio" value="d" name="question5">d) Yenisei River<br>
</div>
<p>
<input type="button" id="init" value="Submit" />
</p>
<p id="results"></p>

Related

Printing a message depending on a specific value

I'm having trouble with a project I am doing for university.
It consists on creating a diabetes risk assessment tool using html forms and javascript.
Basically there are 4 questions, each with 4 possible answers (using radio buttons, and user can only choose one answer per question).
In the end, there will be a "Calculate" button which will calculate the value of the selected answers, sum the values and display a message according the result. Here is the code for the html and javascript:
let calc = document.getElementById('form');
calc.addEventListener('submit', calculateAndPrintRisk);
function calculateRisk() {
let age = document.querySelector('input[name="age"]:checked').value;
let bmi = document.querySelector('input[name="bmi"]:checked').value;
let diabetes = document.querySelector('input[name="diabetes"]:checked').value;
let diet = document.querySelector('input[name="diet"]:checked').value;
return age + bmi + diabetes + diet;
};
function calculateAndPrintRisk(e) {
e.preventDefault();
var risk;
var riskTotal = calculateRisk();
if (riskTotal) {
if (riskTotal <= 15) {
alert("risk is low");
} else if (riskTotal <= 25) {
alert(risk = "medium");
} else {
alert(risk = "high");
}
}
}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript FMA</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<script src="diabetestool.js"> </script>
<body>
<div id="wrapper">
<h1>The Diabetes Risk Assesment Tool</h1>
<div id="Options">
<form id="form">
<p> How old are you? </p>
1-25 <input type="radio" name="age" value="0" checked> 26-40 <input type="radio" name="age" value="5"> 41-60 <input type="radio" name="age" value="8"> 60+ <input type="radio" name="age" value="10">
<p> What is your BMI? </p>
0-25 <input type="radio" name="bmi" value="0" checked> 26-30 <input type="radio" name="bmi" value="0"> 31-35 <input type="radio" name="bmi" value="9"> 35+ <input type="radio" name="bmi" value="10">
<p> Does anybody in your family have diabetes? </p>
No <input type="radio" name="diabetes" value="0" checked> Grandparent <input type="radio" name="diabetes" value="7"> Sibling <input type="radio" name="diabetes" value="15"> Parent <input type="radio" name="diabetes" value="15">
<p> How would you describe your diet? </p>
Low sugar <input type="radio" name="diet" value="0" checked> Normal sugar <input type="radio" name="diet" value="0"> Quite high sugar <input type="radio" name="diet" value="7"> High sugar <input type="radio" name="diet" value="10">
<input type="submit" id="calculate" name="button_calculate" value="Calculate">
</form>
</div>
</div>
</body>
</html>
The code shows no errors, but does not work when I hit Calculate.
Any help would be greatly apreciated, since I am still learning javaScript.
Following 2 statements must have thrown errors -
alert("risk is low";
alert(risk = "high";
Hit F12 while you execute your code on any browser. Look for console in it. You must be seeing errors there.
You don't call your function when you submit your form
You need to add and eventListener to detect when you submit your post, then cancel the Event, call your calcultateRisk function
Your event should be something like that.
document.getElementById('form1').addEventListener('submit', function(evt){
evt.preventDefault();
// do what you want
// call your function
})
You can not use same id for more than one HTML element.
I have updated the code and used querySelector to get the value of radio elements.
let calc = document.getElementById('form');
calc.addEventListener('submit', calculateAndPrintRisk);
function calculateRisk() {
let age = document.querySelector('input[name="age"]:checked').value;
let bmi = document.querySelector('input[name="bmi"]:checked').value;
let diabetes = document.querySelector('input[name="diabetes"]:checked').value;
let diet = document.querySelector('input[name="diet"]:checked').value;
return age + bmi + diabetes + diet;
};
function calculateAndPrintRisk(e) {
e.preventDefault();
var risk;
var riskTotal = calculateRisk();
if (riskTotal) {
if (riskTotal <= 15) {
alert("risk is low");
} else if (riskTotal <= 25) {
alert(risk = "medium");
} else {
alert(risk = "high");
}
}
}
<div id="wrapper">
<h1>The Diabetes Risk Assesment Tool</h1>
<div id="Options">
<form id="form">
<p> How old are you? </p>
1-25 <input type="radio" name="age" value="0" checked> 26-40 <input type="radio" name="age" value="5"> 41-60 <input type="radio" name="age" value="8"> 60+ <input type="radio" name="age" value="10">
<p> What is your BMI? </p>
0-25 <input type="radio" name="bmi" value="0" checked> 26-30 <input type="radio" name="bmi" value="0"> 31-35 <input type="radio" name="bmi" value="9"> 35+ <input type="radio" name="bmi" value="10">
<p> Does anybody in your family have diabetes? </p>
No <input type="radio" name="diabetes" value="0" checked> Grandparent <input type="radio" name="diabetes" value="7"> Sibling <input type="radio" name="diabetes" value="15"> Parent <input type="radio" name="diabetes" value="15">
<p> How would you describe your diet? </p>
Low sugar <input type="radio" name="diet" value="0" checked> Normal sugar <input type="radio" name="diet" value="0"> Quite high sugar <input type="radio" name="diet" value="7"> High sugar <input type="radio" name="diet" value="10">
<input type="submit" id="calculate" name="button_calculate" value="Calculate">
</form>
</div>
</div>
There are a few typos, an unneccessary form ( as you dont want to submit something) and input values are generally strings, which are concatenated through the + operator. You may want to get all checked ones:
[...document.querySelectorAll('input:checked')]
and reduce them to their summed up value:
.reduce((sum,el)=>sum+parseInt(el.value),0);
function calculateRisk() {
return [...document.querySelectorAll('input:checked')].reduce((sum, el) => sum + parseInt(el.value), 0);
}
function calculateAndPrintRisk() {
var riskTotal = calculateRisk();
if (riskTotal <= 15) {
alert("risk is low");
} else if (riskTotal <= 25) {
alert("risk is medium");
} else {
alert("risk is high");
}
}
<div id="wrapper">
<h1>The Diabetes Risk Assesment Tool</h1>
<div id="Options">
<p> How old are you? </p>
1-25 <input type="radio" id="opt" name="age" value="0" checked> 26-40 <input type="radio" id="opt" name="age" value="5"> 41-60 <input type="radio" id="opt" name="age" value="8"> 60+ <input type="radio" id="opt" name="age" value="10">
<p> What is your BMI? </p>
0-25 <input type="radio" id="opt" name="bmi" value="0" checked> 26-30 <input type="radio" id="opt" name="bmi" value="0"> 31-35 <input type="radio" id="opt" name="bmi" value="9"> 35+ <input type="radio" id="opt" name="bmi" value="10">
<p> Does anybody in your family have diabetes? </p>
No <input type="radio" id="opt" name="diabetes" value="0" checked> Grandparent <input type="radio" id="opt" name="diabetes" value="7"> Sibling <input type="radio" id="opt" name="diabetes" value="15"> Parent <input type="radio" id="opt" name="diabetes"
value="15">
<p> How would you describe your diet? </p>
Low sugar <input type="radio" id="opt" name="diet" value="0" checked> Normal sugar <input type="radio" id="opt" name="diet" value="0"> Quite high sugar <input type="radio" id="opt" name="diet" value="7"> High sugar <input type="radio" id="opt" name="diet"
value="10">
<button id="calculate" name="button_calculate" value="Calculate" onclick="calculateAndPrintRisk();">Calculate</button>
</div>
</div>
Note that your if else could be simplified to
function calculateAndPrintRisk(){
alert("your risk is "+(riskTotal<=15?"low":(riskTotal<=25?"medium":"high")));
}

Simple quiz not working in jQuery or JavaScript

I am making a simple quiz to get the number of correct questions answered by a person when he submits the 'submit' button. But, it is always giving Zero. Pls help.
$(document).ready(function(){
$('button').click(function(){
var count = 0;
if($('[name=q1]').val() == "Delhi"){count++;}
if($('[name=q2]').val() == "Lotus"){count++;}
alert(count);
});
});
<body>
<div>
<p>Question: What is capital of India?</p>
<input type="radio" name="q1" value="delhi"> Delhi
<input type="radio" name="q1" value="mumbai"> Mumbai
<input type="radio" name="q1" value="kolkata"> Kolkata
<input type="radio" name="q1" value="lucknow"> Lucknow
</div>
<div>
<p>Question: What is the national flower of India?</p>
<input type="radio" name="q2" value="rose"> Rose
<input type="radio" name="q2" value="lotus"> Lotus
<input type="radio" name="q2" value="sunflower"> Sunflower
<input type="radio" name="q2" value="tulip"> Tulip
</div>
<button>submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
It is always giving '0', but if I select 'Delhi' and 'Lotus' it should give answer as 2.
Two things:
$('[name=q1]').val() will give you the value of the first element with name="q1", not the checked element. For that, add :checked.
You're comparing "delhi" with "Delhi"; case matters.
$(document).ready(function() {
$('button').click(function() {
var count = 0;
if ($('[name=q1]:checked').val() == "delhi") {
count++;
}
if ($('[name=q2]:checked').val() == "lotus") {
count++;
}
alert(count);
});
});
<div>
<p>Question: What is capital of India?</p>
<input type="radio" name="q1" value="delhi"> Delhi
<input type="radio" name="q1" value="mumbai"> Mumbai
<input type="radio" name="q1" value="kolkata"> Kolkata
<input type="radio" name="q1" value="lucknow"> Lucknow
</div>
<div>
<p>Question: What is the national flower of India?</p>
<input type="radio" name="q2" value="rose"> Rose
<input type="radio" name="q2" value="lotus"> Lotus
<input type="radio" name="q2" value="sunflower"> Sunflower
<input type="radio" name="q2" value="tulip"> Tulip
</div>
<button>submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
You have an error in your Js code, and you have to select the checked inputs, your code selects just the first input
$(document).ready(function(){
$('button').click(function(){
var count = 0;
if($('input[name=q1]:checked').val() == "delhi"){count++;}
if($('input[name=q2]:checked').val() == "lotus"){count++;}
alert(count);
});
});
<body>
<div>
<p>Question: What is capital of India?</p>
<input type="radio" name="q1" value="delhi"> Delhi
<input type="radio" name="q1" value="mumbai"> Mumbai
<input type="radio" name="q1" value="kolkata"> Kolkata
<input type="radio" name="q1" value="lucknow"> Lucknow
</div>
<div>
<p>Question: What is the national flower of India?</p>
<input type="radio" name="q2" value="rose"> Rose
<input type="radio" name="q2" value="lotus"> Lotus
<input type="radio" name="q2" value="sunflower"> Sunflower
<input type="radio" name="q2" value="tulip"> Tulip
</div>
<button>submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
</body>
$(document).ready(function(){
$('button').click(function(){
var count = 0;
if($('[name=q1]:checked').val() == "delhi"){count++;}
if($('[name=q2]:checked').val() == "lotus"){count++;}
alert(count);
});
});
<body>
<div>
<p>Question: What is capital of India?</p>
<input type="radio" name="q1" value="delhi"> Delhi
<input type="radio" name="q1" value="mumbai"> Mumbai
<input type="radio" name="q1" value="kolkata"> Kolkata
<input type="radio" name="q1" value="lucknow"> Lucknow
</div>
<div>
<p>Question: What is the national flower of India?</p>
<input type="radio" name="q2" value="rose"> Rose
<input type="radio" name="q2" value="lotus"> Lotus
<input type="radio" name="q2" value="sunflower"> Sunflower
<input type="radio" name="q2" value="tulip"> Tulip
</div>
<button>submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
Try to rename you values with a capital letter (lotus=>Lotus, etc).

Getting radio button values for multiple radio button sets

I'm setting up a multiple choice questionnaire with the responses being handling by radio buttons labelled A, B, C and D.
I want to identify the answer to each question by getting the form ID and the clicked button value, so that, for example, a response using the first set of radio buttons might be 1B and the second, 2D and so on (the form ID script is already up and running).
I need this to work on a page with multiple sets of radio buttons
Here is the HTML:
<form class="toeic_pages" id="1">
<label class="item1">
<input type="radio" value="A" name="toeic"/>
<div class="radio-image"></div>
</label>
<label class="item2">
<input type="radio" value="B" name="toeic"/>
<div class="radio-image"></div>
</label>
<label class="item3">
<input type="radio" value="C" name="toeic"/>
<div class="radio-image"></div>
</label>
<label class="item4">
<input type="radio" value="D" name="toeic"/>
<div class="radio-image"></div>
</label>
</form>
...
<form class="toeic_pages" id="2">
<label class="item1">
<input type="radio" value="A" name="toeic"/>
<div class="radio-image"></div>
</label>
<label class="item2">
<input type="radio" value="B" name="toeic"/>
<div class="radio-image"></div>
</label>
<label class="item3">
<input type="radio" value="C" name="toeic"/>
<div class="radio-image"></div>
</label>
<label class="item4">
<input type="radio" value="D" name="toeic"/>
<div class="radio-image"></div>
</label>
</form>
However, while I've been able to get a checked radio button value using this:
jQuery('input[name=toeic]').change(function(){
var invar = jQuery('input[name=toeic]:checked').val();
alert(invar);
});
The script is only effective within the first row of buttons clicked.
To illustrate, if in the first row of buttons to be accessed, button B is clicked then B is displayed (correct).
But, if in another row, button C clicked, B is displayed (incorrect) .. and B continues to be displayed for all subsequent button clicks. I've checked out the SO pages on this but I haven't been able to find a solution - the issue seems to be multiple sets of radio buttons.
Any help would be very much appreciated
You could do something like this :
$(document).ready(function() {
$("#finish").click(function() {
var answersList = [];
//Loop over all questoins
$(".toeic_pages").each(function() {
var questionId = $(this).attr("id");
var answer = $("input[name='toeic']:checked", $(this)).val();
//if Answer isnt provided do not update the answersList
if (answer !== undefined) {
answersList.push({
question: questionId,
answer: answer
});
}
});
console.log(answersList);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="toeic_pages" id="1">
<label class="item1">
<input type="radio" value="A" name="toeic" />
<div class="radio-image"></div>
</label>
<label class="item2">
<input type="radio" value="B" name="toeic" />
<div class="radio-image"></div>
</label>
<label class="item3">
<input type="radio" value="C" name="toeic" />
<div class="radio-image"></div>
</label>
<label class="item4">
<input type="radio" value="D" name="toeic" />
<div class="radio-image"></div>
</label>
</form>
...
<form class="toeic_pages" id="2">
<label class="item1">
<input type="radio" value="A" name="toeic" />
<div class="radio-image"></div>
</label>
<label class="item2">
<input type="radio" value="B" name="toeic" />
<div class="radio-image"></div>
</label>
<label class="item3">
<input type="radio" value="C" name="toeic" />
<div class="radio-image"></div>
</label>
<label class="item4">
<input type="radio" value="D" name="toeic" />
<div class="radio-image"></div>
</label>
</form>
<button id="finish">Get Answers</button>
I think this is exactly what you need.
$('#1 input').on('change', function() {
alert($('#1').attr('id')+$('input[name=radioName]:checked', '#1').val());
});
$('#2 input').on('change', function() {
alert($('#2').attr('id')+$('input[name=radioName]:checked', '#2').val());
});
$('#3 input').on('change', function() {
alert($('#3').attr('id')+$('input[name=radioName]:checked', '#3').val());
});
$('#4 input').on('change', function() {
alert($('#4').attr('id')+$('input[name=radioName]:checked', '#4').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="1">
Question 1
<br>
<input type="radio" name="radioName" value="A" /> A <br />
<input type="radio" name="radioName" value="B" /> B <br />
<input type="radio" name="radioName" value="C" /> C <br />
</form>
<form id="2">
Question 2
<br>
<input type="radio" name="radioName" value="A" /> A <br />
<input type="radio" name="radioName" value="B" /> B <br />
<input type="radio" name="radioName" value="C" /> C <br />
</form>
<form id="3">
Question 3
<br>
<input type="radio" name="radioName" value="A" /> A <br />
<input type="radio" name="radioName" value="B" /> B <br />
<input type="radio" name="radioName" value="C" /> C <br />
</form>
<form id="4">
Question 4
<br>
<input type="radio" name="radioName" value="A" /> A <br />
<input type="radio" name="radioName" value="B" /> B <br />
<input type="radio" name="radioName" value="C" /> C <br />
</form>
Credits to the owner of this answer #Peter J in this question How can I know which radio button is selected via jQuery?

How can I check if all radio buttons are checked

I have a number of radio buttons with the option, 'yes' or 'no'.
Is there a simple way with jQuery to check if they all have 'yes' selected?
HTML is:
<input type="radio" id="yes1" name="group1" value="yes">Yes<br>
<input type="radio" name="group1" value="No">No<br>
<hr>
<input type="radio" id="yes2" name="group2" value="yes">Yes<br>
<input type="radio" name="group2" value="No">No<br>
<hr>
<input type="radio" id="yes3" name="group3" value="yes">Yes<br>
<input type="radio" name="group3" value="No">No<br>
I'm guessing it's something along the lines of
yes1 = $("#yes1").prop("checked", true);
yes2 = $("#yes2").prop("checked", true);
yes3 = $("#yes2").prop("checked", true);
if (yes1 & yes2 & yes3) {
// do something ?
}
You can rather compare the length of elements with ['value=yes] with elements with ['value=yes] and property :checked:
if($('[value=yes]').length==$('[value=yes]:checked').length){
//all yes elements are checked
}
One way is to check whether all the radios with value as yes is checked
if($('input[type="radio"][value="yes"]').not(':checked').length == 0){
//all checked
}
You may check the count of radio buttons with value != true. If the count is Zero, all radio buttons would be selected.
if(!$('input[type="radio"][value="yes"]').not(':checked').length){
//select all radio buttons with value = yes
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="radio" id="yes1" name="group1" value="yes">Yes
<br>
<input type="radio" name="group1" value="No">No
<br>
<hr>
<input type="radio" id="yes2" name="group2" value="yes">Yes
<br>
<input type="radio" name="group2" value="No">No
<br>
<hr>
<input type="radio" id="yes3" name="group3" value="yes">Yes
<br>
<input type="radio" name="group3" value="No">No
<br>
<input type="button" id="btn" value="Test" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btn").click(function() {
var length = 3;
var isChecked = true;
for (var i = 1; i <= length; i++) {
isChecked = isChecked && ($("#yes" + i).is(":checked"));
}
if (isChecked)
alert("All are checked");
else
alert("All are not checked");
});
});
</script>
</body>
</html>
<input type="radio" id="yes1" name="group1" value="yes" checked>Yes<br>
<input type="radio" name="group1" value="No">No<br>
<hr>
<input type="radio" id="yes2" name="group2" value="yes" checked>Yes<br>
<input type="radio" name="group2" value="No">No<br>
<hr>
<input type="radio" id="yes3" name="group3" value="yes" checked>Yes<br>
<input type="radio" name="group3" value="No">No<br>
var yes1 = $("#yes1").is(":checked")
var yes2 = $("#yes2").is(":checked")
var yes3 = $("#yes3").is(":checked")
//$("#Myradio").is(":checked")
if (yes1 & yes2 & yes3) {
alert('sasa');
//do something
}
FIDDLE
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="radio" id="yes1" name="group1" value="yes">Yes
<br>
<input type="radio" name="group1" value="No">No
<br>
<hr>
<input type="radio" id="yes2" name="group2" value="yes">Yes
<br>
<input type="radio" name="group2" value="No">No
<br>
<hr>
<input type="radio" id="yes3" name="group3" value="yes">Yes
<br>
<input type="radio" name="group3" value="No">No
<br>
<input type="button" id="btn" value="Test" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btn").click(function() {
var length = 3;
var isChecked = true;
for (var i = 1; i <= length; i++) {
isChecked = isChecked && ($("#yes" + i).is(":checked"));
}
if (isChecked)
alert("All are checked");
else
alert("All are not checked");
});
});
</script>
</body>
</html>

How do I validate a form and redirect to a specific URL based on the user's answers?

<form>
<p class="question"> Hold Old are you</p>
<p ><input name="1" type="radio" value="15"> 12</p>
<p ><input name="1" type="radio" value="8"> 45</p>
<p ><input name="1" type="radio" value="2"> 23</p>
<p class="question"> What is you name<p/>
<p ><input name="2" type="radio" > Jerry</p>
<p ><input name="2" type="radio" > Tom</p>
<p ><input name="2" type="radio" > Becky</p>
<p class="question"> Are you single</p>
<p ><input name="3" type="radio" > yes</p>
<p ><input name="3" type="radio" > no</p>
<p ><input name="4" type="radio" > married</p>
</form>
Hello How are you?
I have a form here that ask 3 questions and each have 3 answers has a point and there will be a score:
if the score is >= 91, then after submitting it should take them to 90.html page
if the score is < 90 And >= 21) then after submitting it should take them to 20.html page
if the score is <= 20) then it should take them to the below20.html
the form should validate to make sure all question have an answer chosen
I need some direction on how i should set this up
HELP please thanks
I think I know what you're looking for. Here is a working sample: http://jsfiddle.net/NLJvZ/
var $rs = $(':radio');
$(':button').click(function(){
var $ch = $(':radio:checked');
if($ch.length < 3)
alert('Please answer all questions');
else{
var score = 0;
$ch.each(function(){
score += parseInt($(this).val(), 10);
});
var url = 'below20.html';
if(score >= 91)
url = '90.html';
else if(score < 90 && score >= 21)
url = '20.html';
alert('Going to URL: ' + url);
location.href = url;
}
});
HTML:
<div id="question1">
<h3>What is your name?</h3>
<label>
<input type="radio" name="first1" value="1" />
Tom
</label>
<label>
<input type="radio" name="first2" value="3" />
Jerry
</label>
<label>
<input type="radio" name="first3" value="2" />
Becky
</label>
</div>
<br />
<div id="question2">
<h3>Are you single?</h3>
<label>
<input type="radio" name="second1" value="1" />
Yes
</label>
<label>
<input type="radio" name="second2" value="3" />
No
</label>
<label>
<input type="radio" name="second3" value="2" />
Married
</label>
</div>
<br />
<div id="question3">
<h3>How old are you?</h3>
<label>
<input type="radio" name="third" value="1" />
12
</label>
<label>
<input type="radio" name="third" value="3" />
23
</label>
<label>
<input type="radio" name="third" value="2" />
45
</label>
</div>
<br />
<input type="button" value="Submit" />

Categories