How to sum value of radio button and checkbox in jquery - javascript

I have a code already working which calculates the sum of the radio buttons. I changed my mind in one of the radio button group and decided to make it a checkbox. When I tick items on the checkbox, the sum returns NaN. What would I add/change in my jquery in order for it to recognize the checkbox value?
Here's my code:
JQuery
< script type = "text/javascript" >
function calcscore() {
$(".calc:checked").each(function() {
score += parseInt($(this).val(), 10);
});
$('#price').text(score.toFixed(2));
$("input[name=sum]").val(score)
}
$().ready(function() {
$(".calc").change(function() {
calcscore()
});
});
< /script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<li>
<label>
<input class="calc" type="radio" name="rad1" id="rad1" />
</label>
<input type="hidden" name="rad1" value="100">
</li>
<li>
<label>
<input class="calc" type="checkbox" name="check1" id="check1" value="200" />
</label>
<input type="hidden" name="check1" value="200">
</li>
<p>Total: PHP <span id="price">0</span>
</p>
Appreciate all the help.

This code code should answer your question:
function calcscore() {
score = 0;
$(".calc:checked").each(function () {
score += Number($(this).val());
});
$("#price").text(score.toFixed(2));
$("#sum").val(score)
}
$().ready(function () {
$(".calc").change(function () {
calcscore()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<li>
<label>
<input class="calc" type="radio" name="rad1" id="rad1" value="100" />
</label>
</li>
<li>
<label>
<input class="calc" type="checkbox" name="check1" id="check1" value="200" />
</label>
</li>
<input type="hidden" name="sum" id="sum" value="0">
<p>Total: PHP <span id="price">0</span>
</p>

for your markup and usecase as it stands now in the question.try this
$('.calc').on('click', function() {
var sum = 0;
$('.calc:checked').each(function() {
sum += Number($(this).parent().next().val())
})
$('#price').text(sum)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<li>
<label>
<input class="calc" type="radio" name="rad1" id="rad1" />
</label>
<input type="hidden" name="rad1" value="100">
</li>
<li>
<label>
<input class="calc" type="checkbox" name="check1" id="check1" value="200" />
</label>
<input type="hidden" name="check1" value="200">
</li>
<p>Total: PHP <span id="price">0</span>
</p>
try this,you dont need hidden fields for values.i removed them and used value property of checkbox.
$('.calc').on('click', function() {
var sum = 0;
$('.calc:checked').each(function() {
sum += Number($(this).val())
})
$('#price').text(sum)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<li>
<label>
<input class="calc" type="checkbox" name="check1" value="100" id="rad1" />
</label>
</li>
<li>
<label>
<input class="calc" type="checkbox" name="check1" value="200" id="check1" value="200" />
</label>
</li>
<p>Total: PHP <span id="price">0</span>
</p>

Related

Radio button calculator with nested if Stateme

I am trying to create a pricing calculator that takes all of the checked radio buttons and pushes them into an array where it is added in the end. However, I would like to have one of the radio buttons take the attribute of the first radio button and multiply it by its own value.
I tried nesting an if statement inside of another if statement but it will only seem to add the values of the first if statement and ignore the second.
$(".w-radio").change(function() {
var totalPrice = 0,
values = [];
$("input[type=radio]").each(function() {
if ($(this).is(":checked")) {
if ($(this).is('[name="catering"]')) {
var cateringFunc = (
$(this).val() * $('[name="gastronomy"]').attr("add-value")
).toString();
values.push($(this).val());
}
values.push($(this).val());
totalPrice += parseInt($(this).val());
}
});
$("#priceTotal span").text(totalPrice);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="hack43-radio-group w-radio">
<input type="radio" name="gastronomy" value="0" add-value="10">0<BR>
<input type="radio" name="gastronomy" value="550" add-value="10">550<BR>
<input type="radio" name="gastronomy" value="550" add-value="10">550<BR>
<input type="radio" name="gastronomy" value="550" add-value="10">550<BR>
</label>
<br>
<label class="hack43-radio-group w-radio">
<input type="radio" name="venue" value="0">0<BR>
<input type="radio" name="venue" value="10500">10500<BR>
<input type="radio" name="venue" value="10500">10500<BR>
<input type="radio" name="venue" value="10500">10500<BR>
</label>
<br>
<label class="hack43-radio-group w-radio">
<input type="radio" name="catering" value="0">0<BR>
<input type="radio" name="catering" value="40">40<BR>
<input type="radio" name="catering" value="45">45<BR>
<input type="radio" name="catering" value="60">60<BR>
</label>
<div class="hack42-45-added-value-row">
<div id="priceTotal">
<span>0</span>
</div>
</div>
When the condition is true you should use cateringFunc instead of $(this).val() when pushing into the values array and adding to totalPrice.
I assume you only want to get the added value from the selected radio button, so I added :checked to the selector. Then you also need to provide a default value if none of the gastronomy buttons are checked.
You shouldn't make up new attributes like add-value. If you need custom attributes, use data-XXX. These can be accessed using the jQuery .data() method.
$(".w-radio").change(function() {
var totalPrice = 0,
values = [];
$("input[type=radio]:checked").each(function() {
if ($(this).is('[name="catering"]')) {
var cateringFunc = (
$(this).val() * ($('[name="gastronomy"]:checked').data("add-value") || 0)
);
values.push(cateringFunc.toString());
totalPrice += cateringFunc;
}
values.push($(this).val());
totalPrice += parseInt($(this).val());
});
$("#priceTotal span").text(totalPrice);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="hack43-radio-group w-radio">
<input type="radio" name="gastronomy" value="0" data-add-value="10">0<BR>
<input type="radio" name="gastronomy" value="550" data-add-value="10">550<BR>
<input type="radio" name="gastronomy" value="550" data-add-value="10">550<BR>
<input type="radio" name="gastronomy" value="550" data-add-value="10">550<BR>
</label>
<br>
<label class="hack43-radio-group w-radio">
<input type="radio" name="venue" value="0">0<BR>
<input type="radio" name="venue" value="10500">10500<BR>
<input type="radio" name="venue" value="10500">10500<BR>
<input type="radio" name="venue" value="10500">10500<BR>
</label>
<br>
<label class="hack43-radio-group w-radio">
<input type="radio" name="catering" value="0">0<BR>
<input type="radio" name="catering" value="40">40<BR>
<input type="radio" name="catering" value="45">45<BR>
<input type="radio" name="catering" value="60">60<BR>
</label>
<div class="hack42-45-added-value-row">
<div id="priceTotal">
<span>0</span>
</div>
</div>

jQuery find input where radio is checked

$().ready(function () {
$(".div").find("input").each(function (index) {
if($(this).attr("checked")==true){
console.log("You have checked the"+index);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">
<input name="1" type="radio" >
<input name="1" type="radio" checked="checked" >
<input name="1" type="radio" >
<input name="1" type="radio" >
</div>
Why I cannot use "find" and "each" function to justify which the radio is checked?
The attribute value is 'checked', not true:
if ($(this).attr("checked") == 'checked') {
console.log("You have checked the " + index);
}
Also note that you can make the index retrieval a one-liner using the :checked selector:
$(document).ready(function() {
var index = $(".div").find("input:checked").index();
console.log("You have checked the " + index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">
<input name="1" type="radio">
<input name="1" type="radio" checked="checked">
<input name="1" type="radio">
<input name="1" type="radio">
</div>
console.log("You have checked the " + $("input[name=1]:checked").index());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">
<input name="1" type="radio">
<input name="1" type="radio" checked="checked">
<input name="1" type="radio">
<input name="1" type="radio">
</div>
No need to use .each() use selector :checked
Description: Matches all elements that are checked or selected.
The problem is whenever you perform $(this).attr("checked") it does NOT returns true, instead, it returns checked for the radio's that are checked and undefined for those which aren't checked.
$().ready(function () {
$("div").find("input").each(function (index) {
if($(this).attr("checked")=="checked"){
console.log("You have checked the "+index);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">
<input name="1" type="radio" >
<input name="1" type="radio" checked="checked" >
<input name="1" type="radio" >
<input name="1" type="radio" >
</div>
You can find below fiddle.
$('#myForm input').on('change', function() {
alert($('input[name=radioName]:checked', '#myForm').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="radio" name="radioName" value="1" /> 1 <br />
<input type="radio" name="radioName" value="2" /> 2 <br />
<input type="radio" name="radioName" value="3" /> 3 <br />
</form>
You may use the following code to find the value of the selected radio button:
HTML
<table>
<tr>
<td><input type="radio" name="q12_3" value="1">1</td>
<td><input type="radio" name="q12_3" value="2">2</td>
<td><input type="radio" name="q12_3" value="3">3</td>
<td><input type="radio" name="q12_3" value="4">4</td>
<td><input type="radio" name="q12_3" value="5">5</td>
</tr>
</table>
JQUERY
$(function(){
$("input[type=radio]").click(function(){
alert($('input[name=q12_3]:checked').val());
});
});
FIDDLE

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)
});

using checkboxes for multiple instances

I have this script. Everything is working except I need to make it work with multi-able items. The first set of work perfectly, but I can seam to replicate it on the second and third set of check boxes.
$(".checkall").on('change', function()
{
// all normal checkboxes will have a class "chk_xxxxxx"
// where "xxxx" is the name of the location, e.g. "chk_wales"
// get the class name from the id of the "check all" box
var checkboxesClass = '.chk_' + $(this).attr("id");
// now get all boxes to check
var boxesToCheck = $(checkboxesClass);
// check all the boxes
boxesToCheck.prop('checked', this.checked);
});
$("#check1 input[type=checkbox], #wales").on("change", function()
{
checkBoxes();
});
function checkBoxes()
{
$("#checked").empty();
if($("#check1 input[type=checkbox]:checked").length == $("#check1 input[type=checkbox]").length)
{
$("#wales").prop("checked", true);
// Display the id of the "check all" box
$("#checked").html($("#checked").html() + "<h3>Wales</h3>");
}
else
{
$("#wales").prop("checked", false);
$("#check1 input[type=checkbox]:checked").each(function()
{
$("#checked").html($("#checked").html() + $(this).next().text() + "<br>");
});
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- <input type="checkbox" id="wales" class="checkall" value="1">
<label for="wales" >Check All</label>
<input type="checkbox" id="checkItem1" value="2" class="chk_wales">
<label for="checkItem1" >Item 1</label>
<input type="checkbox" id="checkItem2" value="2" class="chk_wales">
<label for="checkItem2" >Item 2</label>
<input type="checkbox" id="checkItem3" value="2" class="chk_wales">
<label for="checkItem3" >Item 3</label>-->
<hr />
<input type="checkbox" id="wales" class="checkall" value="1">
<label for="wales">Check All</label>
<section id="check1">
<input type="checkbox" id="checkItem1" value="2" class="chk_wales">
<label for="checkItem1">Item 1</label>
<input type="checkbox" id="checkItem2" value="2" class="chk_wales">
<label for="checkItem2">Item 2</label>
<input type="checkbox" id="checkItem3" value="2" class="chk_wales">
<label for="checkItem3">Item 3</label>
</section>
<hr />
<input type="checkbox" id="west" class="checkall" value="3">
<label for="west">Check All</label>
<section id="check2">
<input type="checkbox" id="checkItem4" value="4" class="chk_west">
<label for="checkItem4">Item 1</label>
<input type="checkbox" id="checkItem5" value="4" class="chk_west">
<label for="checkItem5">Item 2</label>
<input type="checkbox" id="checkItem6" value="4" class="chk_west">
<label for="checkItem6">Item 3</label>
</section>
<hr />
<input type="checkbox" id="east" class="checkall" value="5">
<label for="east">Check All</label>
<section id="check3">
<input type="checkbox" id="checkItem7" value="6" class="chk_east">
<label for="checkItem7">Item 1</label>
<input type="checkbox" id="checkItem8" value="6" class="chk_east">
<label for="checkItem8">Item 2</label>
<input type="checkbox" id="checkItem9" value="6" class="chk_east">
<label for="checkItem9">Item 3</label>
</section>
<p>You have selected:</p>
<div id="checked">
</div>
</body>
</html>
Please can anyone help?
Many thanks in advance.
remove checkBoxes() method and replace the last event handlers as (check this fiddle)
//put the event handler directly on the checkboxes inside the section
$( "section input[type='checkbox']" ).on("change", function()
{
console.log( $( this ) );
//get the handle to the parent section
var $parentSection = $( this ).parent();
//compare the number of checked checkboxes with total one
if( $parentSection.find( "input[type='checkbox']:checked" ).length == $parentSection.find( "input[type=checkbox]" ).length )
{
$parentSection.prev().prev().prop("checked", true);
//write checkall's textbox id
$("#checked").append( "<h3>" + $parentSection.prev().prev().attr( "id" ) + "</h3>");
}
else
{
$parentSection.prev().prev().prop("checked", false);
//write each and every checked box's text
$parentSection.find("input[type='checkbox']:checked").each(function()
{
$("#checked").html($("#checked").html() + $(this).next().text() + "<br>");
});
}
});
Following code snippet should fulfill your requirements. Hope this will help you.
var checkedDiv = $("#checked");
$('input[type=checkbox]').on('change', function() {
if (this.className == 'checkall') {
var section = $(this).nextAll('section:first');
section.find('input[type=checkbox]').prop('checked', this.checked);
} else {
var parentSection = $(this).parent();
var checkall = parentSection.prevAll(".checkall:first")
var isEqual = parentSection.find("input[type=checkbox]:checked").length == parentSection.find("input[type=checkbox]").length;
checkall.prop("checked", isEqual);
}
checkedDiv.html('');
$('.checkall').each(function() {
if (this.checked) {
checkedDiv.append('<h3>' + this.id + '</h3><br/>');
} else {
var section = $(this).nextAll('section:first');
section.find("input[type=checkbox]:checked").each(function() {
checkedDiv.append($(this).next().text() + "<br>");
});
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="wales" class="checkall" value="1">
<label for="wales">Check All</label>
<section id="check1">
<input type="checkbox" id="checkItem1" value="2" class="chk_wales">
<label for="checkItem1">Item 1</label>
<input type="checkbox" id="checkItem2" value="2" class="chk_wales">
<label for="checkItem2">Item 2</label>
<input type="checkbox" id="checkItem3" value="2" class="chk_wales">
<label for="checkItem3">Item 3</label>
</section>
<hr />
<input type="checkbox" id="west" class="checkall" value="3">
<label for="west">Check All</label>
<section id="check2">
<input type="checkbox" id="checkItem4" value="4" class="chk_west">
<label for="checkItem4">Item 1</label>
<input type="checkbox" id="checkItem5" value="4" class="chk_west">
<label for="checkItem5">Item 2</label>
<input type="checkbox" id="checkItem6" value="4" class="chk_west">
<label for="checkItem6">Item 3</label>
</section>
<hr />
<input type="checkbox" id="east" class="checkall" value="5">
<label for="east">Check All</label>
<section id="check3">
<input type="checkbox" id="checkItem7" value="6" class="chk_east">
<label for="checkItem7">Item 1</label>
<input type="checkbox" id="checkItem8" value="6" class="chk_east">
<label for="checkItem8">Item 2</label>
<input type="checkbox" id="checkItem9" value="6" class="chk_east">
<label for="checkItem9">Item 3</label>
</section>
<p>You have selected:</p>
<div id="checked"></div>

jQuery (Mobile): get all checked items (checkboxes)

I got trouble finding a solution to this one.
I have an amount of checkboxes, and I want to get how many of them are checked.
Each time a box get checked/unchecked, the value needs to update.
What I have so far:
http://jsfiddle.net/drhmorw5/3/
My code so far:
function selected() {
var i = 0;
$("#names").each(function () {
if ($(this).prop("checked") === true) {
i++;
$("#checked").text("Sum Checked: " + i);
}
})
};
$("#checked").text("Sum Checked: ");
$(function(){
$('#names input[type=checkbox]').change(function(){
$("#checked").text($('#names input[type=checkbox]:checked').length);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<div id="names">
<label>
<input type="checkbox" name="checkbox-0" class="check">Name 1</label>
<label>
<input type="checkbox" name="checkbox-0" class="check">Name 2</label>
<label>
<input type="checkbox" name="checkbox-0" class="check">Name 3</label>
<label>
<input type="checkbox" name="checkbox-0" class="check">Name 4</label>
<label>
<input type="checkbox" name="checkbox-0" class="check">Name 5</label>
<label>
<input type="checkbox" name="checkbox-0" class="check">Name 6</label>
</div>
<br>
<br>
Sum Checked: <span id="checked">0</span>

Categories

Resources