Validation of Multiple radiobox with different name using javascript - javascript

I have the following code. This is a quiz and i want to validate the quiz form in such a way that user have to attempt all the questions. Without answering all the questions user can not proceed to submission. A alertbox should be displayed if any question is not answered.
My code is as follows
<form method="post" action="" name="quizform" id="quizform">
<h4> 1)This is first question</h4>
a) <input type="radio" name="a1" value="1" id="1" /><label for="1">Option 1</label><br />
b) <input type="radio" name="a1" value="2" id="2" /><label for="2">Option 1</label><br />
c) <input type="radio" name="a1" value="3" id="3" /><label for="3">Option 1</label><br />
d) <input type="radio" name="a1" value="4" id="4" /><label for="4">Option 1</label><br />
<h4> 2)This is first question</h4>
a) <input type="radio" name="a2" value="1" id="5" /><label for="5">Option 1</label><br />
b) <input type="radio" name="a2" value="2" id="6" /><label for="6">Option 1</label><br />
c) <input type="radio" name="a2" value="3" id="7" /><label for="7">Option 1</label><br />
d) <input type="radio" name="a2" value="4" id="8" /><label for="8">Option 1</label><br />
<h4> 3)This is first question</h4>
a) <input type="radio" name="a3" value="1" id="9" /><label for="9">Option 1</label><br />
b) <input type="radio" name="a3" value="2" id="10" /><label for="10">Option 1</label><br />
c) <input type="radio" name="a3" value="3" id="11" /><label for="11">Option 1</label><br />
d) <input type="radio" name="a3" value="4" id="12" /><label for="12">Option 1</label><br />
<h4> 4)This is first question</h4>
a) <input type="radio" name="a4" value="1" id="13" /><label for="13">Option 1</label><br />
b) <input type="radio" name="a4" value="2" id="14" /><label for="14">Option 1</label><br />
c) <input type="radio" name="a4" value="3" id="15" /><label for="15">Option 1</label><br />
d) <input type="radio" name="a4" value="4" id="16" /><label for="16">Option 1</label><br />
<input type="submit" onclick="formButtonFever('quizform','submit')" />

hope this will help you
<script LANGUAGE="JavaScript">
function formButtonFever(form){
ErrorText= "";
if ( ( form.a1[0].checked == false ) && ( form.a1[1].checked == false ) && (
form.a1[2].checked == false )&& ( form.a1[3].checked == false ))
{
alert ( "Please answer for 1st question" );
return false;
}
if ( ( form.a2[0].checked == false ) && ( form.a2[1].checked == false ) && (
form.a2[2].checked == false )&& ( form.a2[3].checked == false ))
{
alert ( "Please answer for 2nd question" );
return false;
}
if ( ( form.a3[0].checked == false ) && ( form.a3[1].checked == false ) && (
form.a3[2].checked == false )&& ( form.a3[3].checked == false ))
{
alert ( "Please answer for 3rd question" );
return false;
}
if ( ( form.a4[0].checked == false ) && ( form.a4[1].checked == false ) && (
form.a4[2].checked == false )&& ( form.a4[3].checked == false ))
{
alert ( "Please answer for 4th question" );
return false;
}
if (ErrorText= "") { form.submit() }
}
</script>
<form method="post" action="" name="quizform" id="quizform">
//your code
<input type="submit" onclick="return formButtonFever(this.form)" />
</body>
</html>

I found this example that I think answers your question
<script type="text/javascript">
function validateRadio( obj,correct ){
var result = 0;
for(var i=0; i<obj.length; i++){
if(obj[i].checked==true && obj[i].value==correct){
result = 1;
}
}
if(!result && obj.value == correct){
result = 1;
}
return result
}
function validateSubmit( obj ){
var err = '';
if( !validateRadio( obj.a,3 ) ){ err+='\nFirst radio is wrong'; }
if( !validateRadio( obj.b,2 ) ){ err+='\nSecond radio is wrong'; }
if( err.length ){
alert('Problem:'+err);
return false;
}
else{
alert('Good Job -- Submitting');
return true;
}
}
</script>
<form onsubmit="return validateSubmit(this);" action="#">
Choose "3"
<input type="radio" name="a" value="1" onchange="if(!validateRadio(this,3)) alert('Incorrect');"> 1
<input type="radio" name="a" value="2" onchange="if(!validateRadio(this,3)) alert('Incorrect');"> 2
<input type="radio" name="a" value="3" onchange="if(!validateRadio(this,3)) alert('Incorrect');"> 3
<input type="radio" name="a" value="4" onchange="if(!validateRadio(this,3)) alert('Incorrect');"> 4
<p>Choose "2"
<input type="radio" name="b" value="1"> 1
<input type="radio" name="b" value="2"> 2
<input type="radio" name="b" value="3"> 3
<input type="radio" name="b" value="4"> 4
</p><p><input type="submit" value="Submit">
</p></form>
Reference : http://www.esqsoft.com/javascript/javascript-example-how-to-validate-radio-buttons.htm

One approach is to iterate over the form's elements collection and check that each radio button group has at least one checked:
function checkRadios(form) {
// All elements in the form
var elements = form.elements,
visited = {},
name,
node,
result = true;
// Loop over elements looking for raido button groups
for (var i=0, iLen=elements.length; i<iLen; i++) {
node = elements[i];
name = node.name;
// Store whether one radio in the group is checked
if (node.type == 'radio') {
visited[name] = node.checked || !!visited[name];
}
}
// Deal with unchecked radios
for (name in visited) {
if (visited.hasOwnProperty(name) && !visited[name]) {
console.log(name + ' has not been checked');
result = false;
}
}
// Return false if one group not checked
return result;
}
You should include a reset button in the form too:
<form onsubmit="return checkRadios(this);">
Choose "3"
<input type="radio" name="a" value="1"> 1
<input type="radio" name="a" value="2"> 2
<input type="radio" name="a" value="3"> 3
<input type="radio" name="a" value="4"> 4
<br>
Choose "2"
<input type="radio" name="b" value="1"> 1
<input type="radio" name="b" value="2"> 2
<input type="radio" name="b" value="3"> 3
<input type="radio" name="b" value="4"> 4
<br>
<input type="submit" value="Submit"><input type="reset">
</form>

Another answer. At first you should provide class for each radio button, name a1 have class a1, name a2 have class a2 and so on...Then
try like this..
$("input[type='submit']").click(function()
{ var flag=0;
var a1 = $('.a1').is(':checked');
var a2 = $('.a2').is(':checked');
var a3 = $('.a3').is(':checked');
var a4 = $('.a4').is(':checked');
if(a1 ==false||a2==false||a3==false||a4==false)
{
flag =1;
}
if(flag==1)
{
alert("plaese answer all questions!");
return false;
}
else
{
alert("success");
}
});

Related

Sum of Radio button values printed to the user

I'm very new to html.
I have a survey with two questions where the question choices are presented with radio buttons as this html code shows:
<form>
<p id="description">1. Question 1?</p>
<p>
<label><input type="radio" name="q1" value="5" /> Yes</label>
<label><input type="radio" name="q1" value="0" /> No</label>
</p>
<p id="description">2. Question 2?</p>
<p>
<label><input type="radio" name="q2" value="5" /> Yes</label>
<label><input type="radio" name="q2" value="0" /> No</label>
</p>
</form>
I want to print to the user the sum of his two selections.
So the output could be "You score is 10." if he answered yes to both questions etc.
How can I do this in the simplest way with the code being on the same page as the html code above? Is that possible?
var question1Answers = document.getElementsByName('q1');
var question2Answers = document.getElementsByName('q2');
var answer = 0;
question1Answers.forEach((e) => {
if (e.checked) {
answer += e.value;
break;
}
});
question2Answers.forEach((e) => {
if (e.checked) {
answer += e.value;
break;
}
});
console.log(answer);
please try this:
$("input[type='button']").click(function () {
var score = getChecklistItems();
alert("You score is : " + score);
});
function getChecklistItems() {
var total_score = 0
var result = $("input:radio:checked").get();
var checked_value = $.map(result, function (element) {
return $(element).attr("value");
});
for (i = 0; i < checked_value.length; i++) {
total_score += parseInt(checked_value[i])
}
return total_score
}
<form>
<p id="description">1. Question 1?</p>
<p>
<label><input type="radio" name="q1" value="5" /> Yes</label>
<label><input type="radio" name="q1" value="0" /> No</label>
</p>
<p id="description">2. Question 2?</p>
<p>
<label><input type="radio" name="q2" value="5" /> Yes</label>
<label><input type="radio" name="q2" value="0" /> No</label>
</p>
<p><input type="button" value="Submit"></p>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

js radio buttons check

i am trying to add mutliple choice exam questions (like survey) to my site. For that i am using js and jquery. i added feature to make sure all group buttons have been checked. But the error is that I cannot resolve properly checking of selected ones. Js check only first if and if it is true then all questions have been answered true, if not then all answers are wrong.
here is my js code:
function doAjaxPost() {
var result = 4;
var rightAnswers = 0;
var allmarked = 0;
var response = "";
$('.answers').each(function() {
if ($(this).find('input[type="radio"]:checked').length > 0) {
allmarked = allmarked + 1;
} else {
alert("not all checked");
}
});
if (allmarked == result) {
allmarked = 0;
if ($("input[#name=7]:checked").val() == "right") {
rightAnswers = rightAnswers + 1;
}
if ($("input[#name=8]:checked").val() == "right") {
rightAnswers = rightAnswers + 1;
}
if ($("input[#name=9]:checked").val() == "right") {
rightAnswers = rightAnswers + 1;
}
if ($("input[#name=10]:checked").val() == "right") {
rightAnswers = rightAnswers + 1;
}
$('#info').html(rightAnswers + " / " + result);
}
}
here is my html:
<div class="clearfix single_content">
<div class="tom-right">
<h4 class="tom-right">1.4</h4>
<br />
<ul class="answers">
<input type="radio" name="9" value="1" id="9a" />
<label for="9a">1</label>
<br/>
<input type="radio" name="9" value="2" id="9b" />
<label for="9b">2</label>
<br/>
<input type="radio" name="9" value="3" id="9c" />
<label for="9c">3</label>
<br/>
<input type="radio" name="9" value="right" id="9d" />
<label for="9d">right</label>
<br/>
</ul>
</div>
</div>
<div class="clearfix single_content">
<div class="tom-right">
<h4 class="tom-right">1.5</h4>
<br />
<ul class="answers">
<input type="radio" name="10" value="1" id="10a" />
<label for="10a">1</label>
<br/>
<input type="radio" name="10" value="2" id="10b" />
<label for="10b">2</label>
<br/>
<input type="radio" name="10" value="3" id="10c" />
<label for="10c">3</label>
<br/>
<input type="radio" name="10" value="right" id="10d" />
<label for="10d">right</label>
<br/>
</ul>
</div>
</div>
i am stack to this point. it frankly seems stupid question but i am not spesialized in js. Thus, any assist would be appreciated
Because of this radio group selection, so you can only choose one; if you want to achieve that situation, you need to use checkbox to achieve;and the way to resolve ploblem is every options bind clickevent when clicking one of checkboxes,then the click func can achieve every option choosed
you can try this:
you can create an object with questions and related correct answers:
function doAjaxPost() {
var result = $('.answers').length;
var rightAnswers =0 ;
var response= "" ;
var error=false;
var correct_answers = [{question_number:1,answers_number:5},
{question_number:10,answers_number:2},
{question_number:9,answers_number:3}];
$('.answers').each(function(){
if($(this).find('input[type="radio"]:checked').length > 0){
var question_number=$(this).find('input[type="radio"]:checked').attr("name");
var answer_number =$(this).find('input[type="radio"]:checked').val();
$.each(correct_answers, function( index, value ) {
if(question_number==value.question_number && answer_number==value.answers_number)rightAnswers++;
});
}
else error=true;
});
if(error) alert("not all checked"); //display the error once
else $('#info').html(rightAnswers + " / " + result);
}
$('#check_values').click(function(){
doAjaxPost();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="clearfix single_content">
<div class="tom-right">
<h4 class="tom-right">1.4</h4> <br />
<ul class="answers">
<input type="radio" name="9" value="1" id="9a" />
<label for="9a">1</label><br/>
<input type="radio" name="9" value="2" id="9b" />
<label for="9b">2</label><br/>
<input type="radio" name="9" value="3" id="9c" />
<label for="9c">3</label><br/>
<input type="radio" name="9" value="4" id="9d" />
<label for="9d">4</label><br/>
</ul>
</div>
</div>
<div class="clearfix single_content">
<div class="tom-right">
<h4 class="tom-right">1.5</h4> <br />
<ul class="answers">
<input type="radio" name="10" value="1" id="10a" />
<label for="10a">1</label><br/>
<input type="radio" name="10" value="2" id="10b" />
<label for="10b">2</label><br/>
<input type="radio" name="10" value="3" id="10c" />
<label for="10c">3</label><br/>
<input type="radio" name="10" value="4" id="10d" />
<label for="10d">4</label><br/>
</ul>
</div>
</div>
<input type="button" id="check_values" value="Check"/>
<p id="info"></p>

Show/Hide div if all radios are checked

I have N groups of radios. I would like to show a div if all groups of radios are checked and if not all are checked, show another div:
http://jsfiddle.net/zoLwdqx6/
HTML
<p>
<input type="radio" name="period" value="1" />1 Year
<input type="radio" name="period" value="2" />2 Years
<input type="radio" name="period" value="3" />3 Years
</p>
<br>
<p>
<input type="radio" name="year" value="1" />2015
<input type="radio" name="year" value="2" />2014
<input type="radio" name="year" value="3" />2013
</p>
<br>
<p>
<input type="radio" name="student" value="1" />Paul
<input type="radio" name="student" value="2" />Mary
<input type="radio" name="student" value="3" />Jane
</p>
<br>
<div class="notchecked">[not all checkboxes are selected yet]</div>
<div class="yeschecked">[submit button]</div>
Javascript
$('.yeschecked').hide();
$('input[type=radio]').click(function () {
$('.yeschecked').show();
});
Here is an example where 3 is not hardcoded:
$(function() {
$(".yeschecked").hide();
// count number of radio buttons grouped by name
var radioGroups = [];
$("input[type=radio]").each(function() {
if ($.inArray(this.name, radioGroups) >= 0) {
return;
}
radioGroups.push(this.name);
});
// radioGroups = ["period", "year", "student"]
$("input[type=radio]").on("change", function() {
var all = $("input[type=radio]:checked").length === radioGroups.length;
// using http://api.jquery.com/toggle/#toggle-display
$(".yeschecked").toggle(all);
$(".notchecked").toggle(all === false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>
<input type="radio" name="period" value="1">1 Year
<input type="radio" name="period" value="2">2 Years
<input type="radio" name="period" value="3">3 Years
</p>
<p>
<input type="radio" name="year" value="1">2015
<input type="radio" name="year" value="2">2014
<input type="radio" name="year" value="3">2013
</p>
<p>
<input type="radio" name="student" value="1">Paul
<input type="radio" name="student" value="2">Mary
<input type="radio" name="student" value="3">Jane
</p>
<div class="notchecked">[not all checkboxes are selected yet]</div>
<div class="yeschecked">[submit button]</div>
You can get the checked radio button count if it is three then all categrories are selected
Live Demo
$('.yeschecked').hide();
$('input[type=radio]').change(function () {
if ($('input[type=radio]:checked').length == 3) {
$('.yeschecked').show();
$('.notchecked').hide();
} else {
$('.notchecked').show();
$('.yeschecked').hide();
}
});
This can be done by length
$(document).ready(function(){
var total = totalChecked = 0;
$('input[type=radio]').on("change",function(){
totalChecked = $('input[type=radio]:checked').length;
if( totalChecked == 3 ){
$('.yeschecked').show();
$('. notchecked').hide();
} else {
$('. notchecked').show();
$('.yeschecked').hide();
}
})
});
for length refer Here
Here is a fiddle to the example
As a group only one radio will be selected, so here only 3 radios will be checked.
var totl; // track total radio groups
$(function() {
var rdos = $('input[type=radio]');
rdos.on('change', toggleDivs);
var tmp = [], nm;
rdos.each(function() {
nm = this.name.toLowerCase();
if (-1 === $.inArray(nm, tmp)) //not found in array
tmp.push(nm); // new group
});
totl = tmp.length; // get count of radio groups
toggleDivs(); //page load trigger
});
var toggleDivs = function() {
var chkd = $('input[type=radio]:checked').length;
$('div.notchecked').toggle(chkd !== totl);
$('div.yeschecked').toggle(chkd === totl);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>
<input type="radio" name="period" value="1" />1 Year
<input type="radio" name="period" value="2" />2 Years
<input type="radio" name="period" value="3" />3 Years
</p>
<p>
<input type="radio" name="year" value="1" />2015
<input type="radio" name="year" value="2" />2014
<input type="radio" name="year" value="3" />2013
</p>
<p>
<input type="radio" name="student" value="1" />Paul
<input type="radio" name="student" value="2" />Mary
<input type="radio" name="Student" value="3" />Jane
</p>
<div class="notchecked">[not all checkboxes are selected yet]</div>
<div class="yeschecked">[submit button]</div>

Adding validations to see if radio button is not selected

I have the following code:
<li>1. question 1</li>
<li>
<input type="radio" name="question1" id="sd1" value="1">Strongly Disagree
<input type="radio" name="question1" id="d1" value="2">Disagree
<input type="radio" name="question1" id="n1" value="3">Neither Agree Nor Disagree
<input type="radio" name="question1" id="a1" value="4">Agree
<input type="radio" name="question1" id="sa1" value="5">Strongly Agree
</li>
<br/><br/>
<li>2. question 2 </li>
<li>
<input type="radio" name="question2" id="sd2" value="1">Strongly Disagree
<input type="radio" name="question2" id="d2" value="2">Disagree
<input type="radio" name="question2" id="n2" value="3">Neither Agree Nor Disagree
<input type="radio" name="question2" id="a2" value="4">Agree
<input type="radio" name="question2" id="sa2" value="5">Strongly Agree
</li>
<br/><br/>
<li>3. question 3</li>
<li>
<input type="radio" name="question3" id="sd3" value="1">Strongly Disagree
<input type="radio" name="question3" id="d3" value="2">Disagree
<input type="radio" name="question3" id="n3" value="3">Neither Agree Nor Disagree
<input type="radio" name="question3" id="a3" value="4">Agree
<input type="radio" name="question3" id="sa3" value="5">Strongly Agree
</li>
<br/><br/>
<input type="submit" value="Submit" name="Submit" id="Submit" />
I have such 30 questions. My requirement is that the user must answer all 30 questions.
How do I write javascript function such that a mesage is shown tot he user if he doesnt answer even one of the questions.
EDIT:
The problem with my javascript i sthis:
if ( (thisfrm.question3[0].checked == false) || (thisfrm.question3[1].checked == false) || (thisfrm.question3[2].checked == false) || (thisfrm.question3[3].checked == false) || (thisfrm.question3[4].checked == false))
{
alert('Please answer question 1');
return false;
}
the above code is repeated for every question without loop. i.e. it is written for each ques. but even when all ques are answered,it still displays Please answer question 1
This method makes use of jQuery and checks for unchecked radio buttons in a set of answers
HTML - add a class to your questions <li>
<li>1. question 1</li>
<li class="option">
<input type="radio" name="question1" id="sd1" value="1">Strongly Disagree
<input type="radio" name="question1" id="d1" value="2">Disagree
<input type="radio" name="question1" id="n1" value="3">Neither Agree Nor Disagree
<input type="radio" name="question1" id="a1" value="4">Agree
<input type="radio" name="question1" id="sa1" value="5">Strongly Agree
</li>
Javascript
// Delegate submit action
$(document).on('submit', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.option').each(function () {
// Question text
var question = $(this).prev();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question.text());
question.css('color', 'red'); // Highlight unanswered question
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
Example here http://fiddle.jshell.net/6jNpQ/2/
Below code is more simple and clean for even biggners
if (!$("input[name='html_elements']:checked").val()) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
check out this below fiddle demo
Visit http://jsfiddle.net/creators_guru/DBd79/
Check this. Instead of validating each element you can use something like this
for(var i = 1 ; i <= 30 ; i++)
{
var radios = document.getElementsByName('question'+i);
var checked = false;
for (var j = 0, length = radios.length; j < length; j++)
{
if (radios[j].checked)
{
checked = true;
break;
}
}
if(!checked)
{
alert('Please answer question '+i);
break;
}
}
It looks like you're using only javascript. I recommend you adding jQuery to make writing javascript easier.
Anyway, only using javascript you can try this:
var questions = 30;
var answer_checked = false;
var one_not_checked = false;
for (var i = 1; i <= questions; i++) {
for (var j=0; j < document.getElementsByName('question'+i).length; j++) {
answer_checked = answer_checked || (thisfrm['question'+i][j].checked == true);
}
one_not_checked = one_not_checked || !answer_checked;
answer_checked = false;
}
if (one_not_checked) {
// your message to the user as one answer is not checked
}
Something like this?
if ($('input[type=radio]:checked').length <= 0) {
alert("No radio checked")
}
Or do it by name?
if ($('input[name=question1]:checked').length <= 0) {
alert("No radio checked")
}
You should use logical operator && for your condition
if ( (thisfrm.question3[0].checked == false) &&
(thisfrm.question3[1].checked == false) &&
(thisfrm.question3[2].checked == false) &&
(thisfrm.question3[3].checked == false) &&
(thisfrm.question3[4].checked == false) )
Here is the answer for your question. You can check this also.
Just using this code I have write it for your code. Please see below
HTML Code
<form method="POST" action="/echo/html/?html=;delay=3;">
<ul>
<li class="question">1) question 1</li>
<li class="answers">
<input type="radio" name="question1" id="11" value="1" />Strongly Disagree
<input type="radio" name="question1" id="12" value="2" />Disagree
<input type="radio" name="question1" id="13" value="3" />Neither Agree Nor Disagree
<input type="radio" name="question1" id="14" value="4" />Agree
<input type="radio" name="question1" id="15" value="5" />Strongly Agree
</li>
<li class="question">2) question 2</li>
<li class="answers">
<input type="radio" name="question2" id="21" value="1" />Strongly Disagree
<input type="radio" name="question2" id="22" value="2" />Disagree
<input type="radio" name="question2" id="23" value="3" />Neither Agree Nor Disagree
<input type="radio" name="question2" id="24" value="4" />Agree
<input type="radio" name="question2" id="25" value="5" />Strongly Agree
</li>
<li class="question">3) question 3</li>
<li class="answers">
<input type="radio" name="question3" id="31" value="1" />Strongly Disagree
<input type="radio" name="question3" id="32" value="2" />Disagree
<input type="radio" name="question3" id="33" value="3" />Neither Agree Nor Disagree
<input type="radio" name="question3" id="34" value="4" />Agree
<input type="radio" name="question3" id="35" value="5" />Strongly Agree
</li>
</ul>
<input type="submit" value="Submit" name="Submit" id="Submit" />
</form>
Javascript Code
$("form").submit(function () {
var allChecked = true;
$('li.answers').each(function () {
if (!$(':radio', this).is(':checked')) {
allChecked = false;
return false;
}
});
if (!allChecked) {
alert('Please fill the form completely...');
return false;
} else {
alert('You have filled the complete form.');
}
});
#by javascript
function validate(){
if (checkRadio("question1") && checkRadio("question2") && checkRadio("question3")){
return true;
}else{
alert("Please answer all Questions!");
return false;
}
}
function checkRadio(name){
var radio = document.forms.myForm[name];
for (var option in radio){
if(radio[option].checked){
return true;
}
}
return false;
}

Dynamic alerts with radio buttons

I have this HTML form below (radio buttons) which is having 3 questions with answers A, B and C.
<fieldset>
<legend>Question 1:</legend>
<label><input type="radio" value="1" name="first" />A</label> <br />
<label><input name="first" type="radio" value="2" />B</label> <br />
<label><input name="first" type="radio" value="3" />C</label> <br />
</fieldset>
<fieldset>
<legend>Question 2:</legend>
<label><input type="radio" value="1" name="second" />A</label> <br />
<label><input name="second" type="radio" value="2" />B</label> <br />
<label><input type="radio" value="3" name="second" />C</label> <br />
</fieldset>
<fieldset>
<legend>Question 3:</legend>
<label><input type="radio" value="1" name="third" />A</label> <br />
<label><input name="third" type="radio" value="2" />B</label> <br />
<label><input type="radio" value="3" name="third" />C</label> <br />
</fieldset>
<div id="display">Please answer all the questions</div>​
What I need here is a jQuery script to display 3 answers dynamically. The 3 answers should be like below:
Answer 1 (if 2 or more answers are A)
Answer 2 (if 2 or more answers are B)
Answer 3 (if 2 or more answers are C)
Nothing is displayed if the answers are A, B and C.
I'm not a jQuery pro but I just have the script (below) to check if the answers are completed or not. Can anyone help me with this?
$('input:radio').click(
function() {
var q = $('fieldset').length;
console.log('q: ' + q + '; checked: ' + $('input:radio:checked').length);
if ($('input:radio:checked').length == q){
$('#display').text('You\'ve completed all questions!');
}
else {
$('#display').text('You\'ve not yet finished...');
}
});​
Thanks in advance.
JSFiddle Demo - http://jsfiddle.net/BhanuChawla/KSd3M/
Here is one possible solution:
var answers = {
"1": "Answer 1",
"2": "Answer 2",
"3": "Answer 3"
};
$("input[type='radio']").on("click", function() {
var vals = $("fieldset input:checked").map(function() {
return this.value;
}).get().sort();
for (var i = 0; i < vals.length; i++) {
if (vals[i] == (vals[i + 1] || null)) {
$("#display").text(answers[vals[i]]);
break;
}
}
});​
DEMO: http://jsfiddle.net/mLnWP/
Here i have done complete bins for above issue. you can check demo link too.
Demo: http://codebins.com/bin/4ldqp74
HTML
<fieldset>
<legend>
Question 1:
</legend>
<label>
<input type="radio" value="1" name="first" />
A
</label>
<label>
<input name="first" type="radio" value="2" />
B
</label>
<label>
<input name="first" type="radio" value="3" />
C
</label>
</fieldset>
<fieldset>
<legend>
Question 2:
</legend>
<label>
<input type="radio" value="1" name="second" />
A
</label>
<label>
<input name="second" type="radio" value="2" />
B
</label>
<label>
<input type="radio" value="3" name="second" />
C
</label>
</fieldset>
<fieldset>
<legend>
Question 3:
</legend>
<label>
<input type="radio" value="1" name="third" />
A
</label>
<label>
<input name="third" type="radio" value="2" />
B
</label>
<label>
<input type="radio" value="3" name="third" />
C
</label>
</fieldset>
<div id="display">
Please answer all the questions
</div>
JQuery
$(function() {
var answers = Array();
$("input:radio").click(function() {
var index = 0;
if ($(this).is(":checked")) {
index = $(this).closest("fieldset").index();
answers[index] = $(this).val().trim();
}
for (var i = 0; i < answers.length; i++) {
if ($("input:radio[value=" + answers[i] + "]:checked").length > 1) {
$("#display").text("Max Answers Selected:" + answers[i]);
break;
} else if ($("input:radio:checked").length >= 3) {
$("#display").text("All have different Answers..!");
}
}
});
});
CSS
label{
float:left;
margin-left:10px;
font-size:14px;
}
#display{
margin-top:10px;
border:1px solid #335599;
padding:5px;
font-size:14px;
background:#a4a1df;
}
Demo: http://codebins.com/bin/4ldqp74

Categories

Resources