js radio buttons check - javascript

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>

Related

Retain Multiple Radio Buttons checked after page refresh

In a form there are 2 group of radio buttons.
In the first group named Result, there are 4 option: id="ok", id="fa", id="fp", id="bp".
In the second group named ResultCategories, there are 9 option: id="cat1" .... id="cat9".
What I want:
a. If ok is clicked, ResultCategories will be unchecked (if already checked).
b. If fp or bp is clicked, cat9 of ResultCategories will be checked.
c. If one of the cat1 to cat8 of ResultCategories is clicked, fa of Result will be checked.
d. When radio buttons are clicked page will refresh and checked radio buttons remain checked.
I got a to c working but d is not working. It retains checked radio for only one group.
Here is what tried:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<form action="" method="POST">
<fieldset class="scheduler-border">
<legend class="scheduler-border">Quality Check</legend>
<div style="float: right;">
<button type="submit" id="submit" name="submit" class="btn btn-info">Complete</button>
</div>
<br />
<br />
<br />
<div class="row">
<div class="column">
<div id="Result">
<label>Result:</label>
<label class="radioContainer">Ok
<input type="radio" name="Result" id ="ok" value="1" />
<span class="circle"></span>
</label>
<label class="radioContainer">Fasle Alarm
<input type="radio" name="Result" id="fa" value="2" />
<span class="circle"></span>
</label>
<label class="radioContainer">False Pass
<input type="radio" name="Result" id="fp" value="3" />
<span class="circle"></span>
</label>
<label class="radioContainer">Blatant Pass
<input type="radio" name="Result" id="bp" value="4" />
<span class="circle"></span>
</label>
</div>
</div>
<br />
<div class="column">
<div id="ResultCategories">
<label>Result Categories:</label>
<div>
<label class="radioContainer">Cat 1
<input type="radio" name="ResultCategories" id="cat1" value="1" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 2
<input type="radio" name="ResultCategories" id="cat2" value="2" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 3
<input type="radio" name="ResultCategories" id="cat3" value="3" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 4
<input type="radio" name="ResultCategories" id="cat4" value="4" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 5
<input type="radio" name="ResultCategories" id="cat5" value="5" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 6
<input type="radio" name="ResultCategories" id="cat6" value="6" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 7
<input type="radio" name="ResultCategories" id="cat7" value="7" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 8
<input type="radio" name="ResultCategories" id="cat8" value="8" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 9
<input type="radio" name="ResultCategories" id="cat9" value="9" />
<span class="circle"></span>
</label>
</div>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</body>
<script> $('input:radio').click(function() {
location.reload(); }); </script>
I have added a fiddle here: Fiddle
$(document).ready(function() {
var result_dom = $('input[name="Result"]');
var categories_dom = $('input[name="ResultCategories"]');
var cat9 = $('#cat9');
var fa = $('#fa')
result_dom.on('change', function() {
var checked_val = $(this).val();
if (checked_val == 1) {
categories_dom.prop('checked', false);
} else if (checked_val == 3 || checked_val == 4) {
cat9.prop('checked', true);
}
});
categories_dom.on('change', function() {
var checked_val = $(this).val();
if (checked_val >= 1 && checked_val <= 8) {
fa.prop('checked', true);
}
});
});
$(document).ready(function(){
if(localStorage.selected) {
$('#' + localStorage.selected ).attr('checked', true);
}
$('.radio').click(function(){
localStorage.setItem("selected", this.id);
});
});
How can I retain both group of radio buttons checked?
Updated Code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var result_dom = $('input[name="Result"]');
var categories_dom = $('input[name="ResultCategories"]');
var cat9 = $('#cat9');
var fa = $('#fa')
result_dom.on('change', function() {
var checked_val = $(this).val();
if (checked_val == 1) {
categories_dom.prop('checked', false);
} else if (checked_val == 3 || checked_val == 4) {
cat9.prop('checked', true);
}
});
categories_dom.on('change', function() {
var checked_val = $(this).val();
if (checked_val >= 1 && checked_val <= 8) {
fa.prop('checked', true);
}
});
});$(document).ready(function() {
var result_dom = $('input[name="Result"]');
var categories_dom = $('input[name="ResultCategories"]');
var cat9 = $('#cat9');
var fa = $('#fa')
result_dom.on('change', function() {
var checked_val = $(this).val();
if (checked_val == 1) {
categories_dom.prop('checked', false);
} else if (checked_val == 3 || checked_val == 4) {
cat9.prop('checked', true);
}
});
categories_dom.on('change', function() {
var checked_val = $(this).val();
if (checked_val >= 1 && checked_val <= 8) {
fa.prop('checked', true);
}
});
});
$(document).ready(function(){
//get the selected radios from storage, or create a new empty object
var radioGroups = JSON.parse(localStorage.getItem('selected') || '{}');
//loop over the ids we previously selected and select them again
Object.values(radioGroups).forEach(function(radioId){
document.getElementById(radioId).checked = true;
});
//handle the click of each radio
$('.radio').on('click', function(){
//set the id in the object based on the radio group name
//the name lets us segregate the values and easily replace
//previously selected radios in the same group
radioGroups[this.name] = this.id;
//finally store the updated object in storage for later use
localStorage.setItem("selected", JSON.stringify(radioGroups));
});
});
</script>
</head>
<body>
<div class="container">
<form action="" method="POST">
<fieldset class="scheduler-border">
<legend class="scheduler-border">Quality Check</legend>
<div style="float: right;"><button type="submit" id="submit" name="submit" class="btn btn-info">Complete</button></div>
<br /> <br /> <br />
<div class="row">
<div class="column">
<div id="Result">
<label>Result:</label>
<label class="radioContainer">Ok
<input class="radio" type="radio" name="Result" id ="ok" value="1">
<span class="circle"></span>
</label>
<label class="radioContainer">Fasle Alarm <input class="radio" type="radio" name="Result" id="fa" value="2">
<span class="circle"></span>
</label>
<label class="radioContainer">False Pass <input class="radio" type="radio" name="Result" id="fp" value="3" >
<span class="circle"></span>
</label>
<label class="radioContainer">Blatant Pass <input class="radio" type="radio" name="Result" id="bp" value="4">
<span class="circle"></span>
</label>
</div>
</div>
<br />
<div class="column">
<div id="ResultCategories"><label>Result Categories:</label>
<div>
<label class="radioContainer">Cat 1 <input class="radio" type="radio" name="ResultCategories" id="cat1" value="1">
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 2 <input class="radio" type="radio" name="ResultCategories" id="cat2" value="2">
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 3 <input class="radio" type="radio" name="ResultCategories" id="cat3" value="3">
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 4 <input class="radio" type="radio" name="ResultCategories" id="cat4" value="4">
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 5 <input class="radio" type="radio" name="ResultCategories" id="cat5" value="5">
<span class="circle"></span>
</label> <label class="radioContainer">Cat 6 <input class="radio" type="radio" name="ResultCategories" id="cat6" value="6">
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 7 <input class="radio" type="radio" name="ResultCategories" id="cat7" value="7">
<span class="circle"></span>
</label> <label class="radioContainer">Cat 8 <input class="radio" type="radio" name="ResultCategories" id="cat8" value="8">
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 9 <input class="radio" type="radio" name="ResultCategories" id="cat9" value="9">
<span class="circle"></span>
</label>
</div>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</body>
<script>
$('input:radio').click(function() {
location.reload();
});
</script>
$(document).ready(function(){
//get the selected radios from storage, or create a new empty object
var radioGroups = JSON.parse(localStorage.getItem('selected') || '{}');
//loop over the ids we previously selected and select them again
Object.values(radioGroups).forEach(function(radioId){
document.getElementById(radioId).checked = true;
});
//handle the click of each radio
$('.radio').on('click', function(){
//set the id in the object based on the radio group name
//the name lets us segregate the values and easily replace
//previously selected radios in the same group
radioGroups[this.name] = this.id;
//finally store the updated object in storage for later use
localStorage.setItem("selected", JSON.stringify(radioGroups));
});
});

Juqey Hide issue

Actually I am showing + button when count is more than 5 otherwise it will hide. when the label count is more than 5 means like if count is 7 it should show "+2more" this is coming properly. When I click + button means + button should hide and - button should appear and also when I click on - button means + button should hide is what I want?
HTML code,
<div id="filter-group21" class="cf">
<!--<input type="text" id="dino-search_21" placeholder="Search By FABRIC"> -->
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="144" />
Chiffon </label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="145" />
Corduroy </label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="146" />
Cotton </label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="147" />
Crepe</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="148" />
Denim</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="162" />
Silk</label>
<button class="loadMore" title="Load more">+</button>
<button class="showLess" title="Load more">-</button>
</ul>
</div>
<div id="filter-group22" class="cf">
<!--<input type="text" id="dino-search_22" placeholder="Search By Brands"> -->
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="149" />
Go Colors</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="150" />
Comfort Lady</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="151" />
Morrio</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="152" />
Twin Birds</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="153" />
Fashion For U (FFU)</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="163" />
Test</label>
<button class="loadMore" title="Load more">+</button>
<button class="showLess" title="Load more">-</button>
</ul>
</div>
Jquery code,
//Hide initially load more & show less for all filters
$(".showLess").hide();
$(".loadMore").hide();
// used to hide filters which are > 5 in filter groups
$('#filter-group21').each(function(){
var label_count = 1;
limit = 5;
label_count = $(this).find('label').length;
more_labels = label_count - limit;
//alert(label_count);return false;
// alert(label_count);return false;
$(this).find('label:gt(4)').hide();
// $(this).find('div:gt(5)').hide();
// display load more if there are more than 5 filters
$(this).find(".loadMore").toggle(label_count > 5);
// $('.loadMore').empty();
if(label_count > 1){
$('.loadMore').append(more_labels + ' more');
}
});
$('#filter-group22').each(function(){
var label_count = 1;
limit = 5;
label_count1 = $(this).find('label').length;
more_labels = label_count1 - limit;
//alert(label_count);return false;
// alert(label_count);return false;
$(this).find('label:gt(4)').hide();
// $(this).find('div:gt(5)').hide();
// display load more if there are more than 5 filters
$(this).find(".loadMore").toggle(label_count1 > 5);
// $('.loadMore').empty();
if(label_count1 > 1){
$('.loadMore').append(more_labels + ' more');
}
});
// On click of + button need to show rest of the filter elements
$('.loadMore').click(function() {
$(this).next().show();
$(this).parent().find('label').show();
// $('.loadMore').hide();
// $(this).parent().find('div').show();
});
// On click of - button need to show only top 5 filter elements
$('.showLess').click(function() {
$(this).hide();
$(this).parent().find('label').not(':lt(5)').hide();
});
Are you looking something like this? This is my wild guess as your question is not very clear to many of us.
//Hide initially load more & show less for all filters
$(".showLess").hide();
$(".loadMore").hide();
// used to hide filters which are > 5 in filter groups
$('#filter-group21').each(function(){
var label_count = 1;
limit = 5;
label_count = $(this).find('label').length;
more_labels = label_count - limit;
//alert(label_count);return false;
// alert(label_count);return false;
$(this).find('label:gt(4)').hide();
// $(this).find('div:gt(5)').hide();
// display load more if there are more than 5 filters
$(this).find(".loadMore").toggle(label_count > 5);
// $('.loadMore').empty();
if(label_count > 1){
$('#filter-group21 .loadMore').append(more_labels + ' more');
}
});
$('#filter-group22').each(function(){
var label_count = 1;
limit = 5;
label_count1 = $(this).find('label').length;
more_labels = label_count1 - limit;
//alert(label_count);return false;
// alert(label_count);return false;
$(this).find('label:gt(4)').hide();
// $(this).find('div:gt(5)').hide();
// display load more if there are more than 5 filters
$(this).find(".loadMore").toggle(label_count1 > 5);
// $('.loadMore').empty();
if(label_count1 > 1){
$('#filter-group22 .loadMore').append(more_labels + ' more');
}
});
// On click of + button need to show rest of the filter elements
$('.loadMore').click(function() {
$(this).next().show();
$(this).parent().find('label').show();
$(this).hide();
// $('.loadMore').hide();
// $(this).parent().find('div').show();
});
// On click of - button need to show only top 5 filter elements
$('.showLess').click(function() {
$(this).prev().show();
$(this).hide();
$(this).parent().find('label').not(':lt(5)').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="filter-group21" class="cf">
<!--<input type="text" id="dino-search_21" placeholder="Search By FABRIC"> -->
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="144" />
Chiffon </label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="145" />
Corduroy </label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="146" />
Cotton </label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="147" />
Crepe</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="148" />
Denim</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="162" />
Silk</label>
<button class="loadMore" title="Load more">+</button>
<button class="showLess" title="Load more">-</button>
</div>
<div id="filter-group22" class="cf">
<!--<input type="text" id="dino-search_22" placeholder="Search By Brands"> -->
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="149" />
Go Colors</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="150" />
Comfort Lady</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="151" />
Morrio</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="152" />
Twin Birds</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="153" />
Fashion For U (FFU)</label>
<label class="checkbox cb_test" >
<input name="filter[]" type="checkbox" value="163" />
Test</label>
<button class="loadMore" title="Load more">+</button>
<button class="showLess" title="Load more">-</button>
</div>
You can refactor your jquery code like below
//Hide initially load more & show less for all filters
$(".showLess").hide();
$(".loadMore").hide();
$('.cf').each(function(){
var label_count = 1;
limit = 5;
label_count1 = $(this).find('label').length;
more_labels = label_count1 - limit;
//alert(label_count);return false;
// alert(label_count);return false;
$(this).find('label:gt(4)').hide();
// $(this).find('div:gt(5)').hide();
// display load more if there are more than 5 filters
$(this).find(".loadMore").toggle(label_count1 > 5);
// $('.loadMore').empty();
if(label_count1 > 1){
$(this).find('.loadMore').append(more_labels + ' more');
}
});
// On click of + button need to show rest of the filter elements
$('.loadMore').click(function() {
$(this).next().show();
$(this).parent().find('label').show();
$(this).hide();
});
// On click of - button need to show only top 5 filter elements
$('.showLess').click(function() {
$(this).hide();
$(this).parent().find('label').not(':lt(5)').hide();
$(this).parent().find('.loadMore').show()
});
Working jsfiddle is https://jsfiddle.net/zt0g3jxo/
I have tried to provide my solution rather than fixing your code. Here's the function which controlling the main things. Here's a Working Fiddle
function hideShow(elem){
var $lMore = $(elem).find('.loadMore').show();
var $sLess = $(elem).find('.showLess').hide();
var $elems = $(elem).children('label');
var elemLen = $(elem).children('label').length;
if(elemLen > showLimit){
$elems.slice(showLimit).hide();
$lMore.html('+'+(elemLen - showLimit) + ' more');
}
}
var showLimit = 5;
$('.cf').each(function() {
hideShow(this);
})
$('.loadMore').on('click', function() {
$(this).parent().children().show();
$(this).hide();
})
$('.showLess').on('click', function() {
hideShow($(this).parent());
})
function hideShow(elem) {
var $lMore = $(elem).find('.loadMore').show();
var $sLess = $(elem).find('.showLess').hide();
var $elems = $(elem).children('label');
var elemLen = $(elem).children('label').length;
if (elemLen > showLimit) {
$elems.slice(showLimit).hide();
$lMore.html('+' + (elemLen - showLimit) + ' more');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="filter-group21" class="cf">
<!--<input type="text" id="dino-search_21" placeholder="Search By FABRIC"> -->
<label class="checkbox cb_test">
<input name="filter[]" type="checkbox" value="144" />
Chiffon </label>
<label class="checkbox cb_test">
<input name="filter[]" type="checkbox" value="145" />
Corduroy </label>
<label class="checkbox cb_test">
<input name="filter[]" type="checkbox" value="146" />
Cotton </label>
<label class="checkbox cb_test">
<input name="filter[]" type="checkbox" value="147" />
Crepe</label>
<label class="checkbox cb_test">
<input name="filter[]" type="checkbox" value="148" />
Denim</label>
<label class="checkbox cb_test">
<input name="filter[]" type="checkbox" value="162" />
Silk</label>
<button class="loadMore" title="Load more">+</button>
<button class="showLess" title="Load more">-</button>
</div>
<div id="filter-group22" class="cf">
<!--<input type="text" id="dino-search_22" placeholder="Search By Brands"> -->
<label class="checkbox cb_test">
<input name="filter[]" type="checkbox" value="149" />
Go Colors</label>
<label class="checkbox cb_test">
<input name="filter[]" type="checkbox" value="150" />
Comfort Lady</label>
<label class="checkbox cb_test">
<input name="filter[]" type="checkbox" value="151" />
Morrio</label>
<label class="checkbox cb_test">
<input name="filter[]" type="checkbox" value="152" />
Twin Birds</label>
<label class="checkbox cb_test">
<input name="filter[]" type="checkbox" value="153" />
Fashion For U (FFU)</label>
<label class="checkbox cb_test">
<input name="filter[]" type="checkbox" value="163" />
Test</label>
<button class="loadMore" title="Load more">+</button>
<button class="showLess" title="Load more">-</button>
</div>

Hide previous html section within jQuery

The code given below is used to check whether the provided answer is right or not, the answer can be selected using radio button. When next button is clicked then 1st question must be hided and next question should be displayed. I need another button "previous" which should display previous question if it is clicked and the current question must be hided.
<div id="question_2" class='questions'>
<h2 id="question_2">2.Questions</h2>
<div class='align'>
<input type="radio" value="1" id='radio1_2' name='2'>
<label id='ans1_2' for='1'>Answer 1</label>
<br/>
<input type="radio" value="2" id='radio2_2' name='2'>
<label id='ans2_2' for='1'>Answer 2</label>
<br/>
<input type="radio" value="3" id='radio3_2' name='2'>
<label id='ans3_2' for='1'>Answer 3</label>
<br/>
<input type="radio" value="4" id='radio4_2' name='2'>
<label id='ans4_2' for='1'>Answer 4</label>
<input type="radio" checked='checked' value="5" style='display:none' id='radio4_2' name='2'>
</div>
<br/>
<input type="button" id='next2' value='Next' name='question' class='button'/>
<input type="button" id="previous" value="Previous" name="question" class="button"/>
</div>
$(document).ready(function(){
$('#demo1').stopwatch().stopwatch('start');
var steps = $('form').find(".questions");
var count = steps.size();
steps.each(function(i){
hider=i+2;
if (i == 0) {
$("#question_" + hider).hide();
createNextButton(i);
}
else if(count==i+1){
var step=i + 1;
//$("#next"+step).attr('type','submit');
$("#next"+step).on('click',function(){
submit();
});
}
else{
$("#question_" + hider).hide();
createNextButton(i);
}
});
function submit(){
$.ajax({
type: "POST",
url: "ajax.php",
data: $('form').serialize(),
success: function(msg) {
$("#quiz_form,#demo1").addClass("hide");
$('#result').show();
$('#result').append(msg);
}
});
}
function createNextButton(i){
var step = i + 1;
var step1 = i + 2;
$('#next'+step).on('click',function(){
$("#question_" + step).hide();
$("#question_" + step1).show();
});
}
setTimeout(function() {
submit();
}, 50000);
});
Check this:
I used the currentStep input to see easily on which question we are.
If you like on the next or previous button you can check if you're on the first or in the last question to hide or show next and previous buttons.
When you're on the last question and you click on next it will raise the submit. I changed it with an alert to see it.
https://jsfiddle.net/netvicious/7hzgdzcp/
<input type='text' id='currentStep' value='1'>
<div id="question_1" class='questions'>
<h2>Question 1</h2>
<div class='align'>
<input type="radio" value="1" id='radio1_1' name='1' />
<label id='ans1_1' for='1'>Answer 1</label>
<br/>
<input type="radio" value="2" id='radio2_1' name='1' />
<label id='ans2_1' for='1'>Answer 2</label>
<br/>
<input type="radio" value="3" id='radio3_1' name='1' />
<label id='ans3_1' for='1'>Answer 3</label>
<br/>
<input type="radio" value="4" id='radio4_1' name='1' />
<label id='ans4_1' for='1'>Answer 4</label>
</div>
</div>
<div id="question_2" class='questions'>
<h2>Question 2</h2>
<div class='align'>
<input type="radio" value="1" id='radio1_2' name='2' />
<label id='ans1_2' for='2'>Answer 1</label>
<br/>
<input type="radio" value="2" id='radio2_2' name='2' />
<label id='ans2_2' for='2'>Answer 2</label>
<br/>
<input type="radio" value="3" id='radio3_2' name='2' />
<label id='ans3_2' for='2'>Answer 3</label>
<br/>
<input type="radio" value="4" id='radio4_2' name='2' />
<label id='ans4_2' for='2'>Answer 4</label>
</div>
</div>
<br/>
<input type="button" id='next' value='Next' name='question' class='button' />
<input type="button" id="previous" value="Previous" name="question" class="button" />
</div>
$(document).ready(function() {
steps = $('.questions').size();
$('.questions').hide();
$("#question_1").show();
$('#next').on('click', function() {
$('.questions').hide();
elem = parseInt(parseInt($('#currentStep').val()) + 1);
if (elem == steps + 1) {
submit(); // If the current one was the last submit
} else {
$("#question_" + elem).show();
$('#currentStep').val(elem);
}
});
$('#previous').on('click', function() {
elem = parseInt(parseInt($('#currentStep').val()) - 1);
if (elem == 0) return; // It was the first question so no previous one
$('.questions').hide();
$("#question_" + elem).show();
$('#currentStep').val(elem);
});
function submit() {
alert('posting');
exit;
$.ajax({
type: "POST",
url: "ajax.php",
data: $('form').serialize(),
success: function(msg) {
$("#quiz_form,#demo1").addClass("hide");
$('#result').show();
$('#result').append(msg);
}
});
}
});

Calculate total on checkbox checked

HTML
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" /><label for="cat_1">cat_1</label><br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" /><label for="cat_2">cat_2</label><br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" /><label for="cat_3">cat_3</label><br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" /><label for="cat_4">cat_4</label><br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" /><label for="cat_5">cat_5</label><br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" /><label for="cat_6">cat_6</label><br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" /><label for="cat_7">cat_7</label><br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" /><label for="cat_8">cat_8</label><br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" /><label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Javascript
function calcAndShowTotal(){
var total = 0;
$('#catlist :checkbox[checked]').each(function(){
total =+ parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#pricelist :checkbox').click(function(){
calcAndShowTotal();
});
calcAndShowTotal();
I am getting particular value. WHY? I tried sum of total, i tried jquery but no success..
Use $('#catlist :checkbox:checked') selector to select checked check-boxes
[] is used as attribute selector and it could be used as '[type="checkbox"]' but it will not filter checked check-boxes
+ operator is not needed before parseFloat, it has to be total =+
Instead of calling handler, just invoke change handler using .change()
function calcAndShowTotal() {
var total = 0;
$('#catlist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#catlist :checkbox').change(calcAndShowTotal).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" />
<label for="cat_1">cat_1</label>
<br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" />
<label for="cat_2">cat_2</label>
<br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" />
<label for="cat_3">cat_3</label>
<br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" />
<label for="cat_4">cat_4</label>
<br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" />
<label for="cat_5">cat_5</label>
<br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" />
<label for="cat_6">cat_6</label>
<br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" />
<label for="cat_7">cat_7</label>
<br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" />
<label for="cat_8">cat_8</label>
<br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" />
<label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Using Array#reduce
function calcAndShowTotal() {
var total = [].reduce.call($('#catlist :checkbox:checked'), function(a, b) {
return a + +$(b).attr('price') || 0;
}, 0);
$('#total').val(total);
}
$('#catlist :checkbox').change(calcAndShowTotal).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" />
<label for="cat_1">cat_1</label>
<br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" />
<label for="cat_2">cat_2</label>
<br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" />
<label for="cat_3">cat_3</label>
<br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" />
<label for="cat_4">cat_4</label>
<br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" />
<label for="cat_5">cat_5</label>
<br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" />
<label for="cat_6">cat_6</label>
<br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" />
<label for="cat_7">cat_7</label>
<br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" />
<label for="cat_8">cat_8</label>
<br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" />
<label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Instead of looping you can use change which will respond to and change event on the checkbox. Also you need add or subtract value like this += for addition on -= for subtraction
var _total = 0;
$('input[type="checkbox"]').change(function() {
if($(this).is(':checked')){
_total += parseFloat($(this).attr('price')) || 0;
}
else{
_total -= parseFloat($(this).attr('price')) || 0;
}
$('#total').val(_total);
})
JSFIDDLE
$('input:checkbox').change(function(){
var totalprice=0;
$('input:checkbox:checked').each(function(){
totalprice+= parseFloat($(this).attr('price'));
});
$('#total').val(totalprice)
});

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