Javascript checkbox values - javascript

I have this javascript code, that substracts from a total sum, a value when a checkbox is checked. In my case for each checkbox checked it substracts 20.
<script language="JavaScript">
function Calculate(){
var tag = window.document.getElementsByClassName("hsnb"), total = <? echo $total; ?>;
for (var i in tag){
total -= tag[i].checked && !isNaN(Number(20)) ? Number(20) : 0;
}
var cucu = + total.toFixed(2);
if(cucu < "20"){
alert("You dont have enough points!");
for(i = 1; document.getElementById("bifa" + i) !== null; i++) {
if (document.getElementById("bifa" + i).checked){
} else {
document.getElementById("bifa" + i).disabled = true;
}
}
}
window.document.getElementById("outputDiv").innerHTML = '<span style="font-size:20px;">You have: POINTS' + cucu + '</span>';
}​
</script>
I want to give each checkbox a certain value, let's say:
<input type="checkbox" id="check" name="check" value="10">
<input type="checkbox" id="check" name="check" value="20">
And if i check the first checkbox it should substract 10 and if i check the second checkbox substract 20. You know what i mean, substract the value for each checkbox. Can you help me with this?

Hi you should try using jQuery, something like
var sub = 0;
jQuery("input[name=check]:checked").each(function(index, element){
sub = sub + jQuery(element).val();
});
var total = yourNumber - sub;
I'haven't tested this snippet but it should work
Hope it helps

In plain javascript you can attach an event to each input an check the "checked" property each time the handler is invoked; if true then substract the input value from the total sum:
<input type="checkbox" id="check" name="check" value="10">
<input type="checkbox" id="check" name="check" value="20">
<script type="text/javascript">
window.onload = function(){
var aBox = document.getElementsByTagName("input"), iTotal = <? echo $total; ?>;
Array.prototype.forEach.call(aBox,function(oCheck, iIdx,aBox){
oCheck.onclick = function(){
if(this.checked){
iTotal = iTotal - this.value;
console.log(iTotal);
}
}
});
}
</script>

Related

How to insert price based on checkbox checked

I have a form where I calculate the price based on the checkboxes checked. But I am having trouble as its not updating the final price correctly. I did some jQuery coding but it's not functioning properly. How can I debug the code and fix it?
//Price Calculator
$(document).ready(function(){
function Calculator(){
let totalAmount = 0;
if($('input[datasource=service_0]').is(':checked')){ // First Checkbox targeted using datasource attribute
totalAmount = 395;
return totalAmount;
}else if($('input[datasource=service_1]').is(':checked')){ // First Checkbox targeted using datasource attribute
totalAmount = 392;
return totalAmount;
}else if ($("input[datasource=service_0]:checked,input[datasource=service_1]:checked").length == 2) {
totalAmount = 397;
return totalAmount;
}
}
//Insert Updated Amount to Budget field
$("input[type=checkbox]").on("click", function(){
if ($("input[datasource=service_0]:checked,input[datasource=service_1]:checked").length == 2){
$("input[name=wpcf-book-amount]").val(Calculator());
} else{
$("input[name=wpcf-book-amount]").val(Calculator());
}
})
})
<div class="extra-services">
<ul>
<li>
<input type="checkbox" name="wpcf-additional-services[]" data-value="5" id="wpcf-fields-checkboxes-option-d41b805f6cbf1d0ab6ee12b8dda8b47d-1" datasource="service_0">
<label for="wpcf-additional-services">Cot (EUR 5)</label>
</li>
<li>
<input type="checkbox" name="wpcf-additional-services[]" data-value="2" id="wpcf-fields-checkboxes-option-d41b805f6cbf1d0ab6ee12b8dda8b47d-1" datasource="service_1">
<label for="wpcf-additional-services">BABY CHAIR (EUR 2)</label>
</li>
</ul>
<input type="text" name="wpcf-booking-amount" id="booking_field" placeholder="Booking Amount (System Generated)" readonly>
</div>
Form containing the fields responsible to calculate the booking amount
<html>
<head></head>
<body>
<input type="checkbox" id="1st" onclick="ge()" value=500>
<label for="1st"> I have a bike</label><br>
<input type="checkbox" id="2nd" onclick ="ye()" value=200>
<label for="2nd"> I have a car</label>
<input type="number" id="here" value="0">
<script>
var amt = 0;
var st = document.getElementById("1st");
var nd = document.getElementById("2nd");
var num = document.getElementById("here");
function ge() {
if(st.checked == true ){
var g = parseInt(st.value);
amt = amt + g;
num.value = amt ;
}
else{
amt = amt - parseInt(st.value);
num.value = amt;
}
}
function ye() {
if(nd.checked == true){
var g = parseInt(nd.value);
amt = amt + g;
num.value = amt ;
}
else{
amt = amt - parseInt(nd.value);
num.value = amt;
}
}
</script>
</body>
</html>
Here you go if it's only for two checkbox this will work, for live demo click here

start a function if another function is active and activate some checkboxes only - JQuery

i Have a function that I want to start only if another function is previously activated.
I have some CheckBoxes and I need to sum its values to get the total.
Only When a user has selected some of the CheckBoxes it must activate another checkbox with a discount.
I want that the discount checkbox get activated after the first selection because, if I don't do so, I could have a negative price.
Then (if it's possible) I want that the discount checkbox get deactivated is a user deselect all the previous CheckBoxes.
Is this possible?
Here's my script. I'm super new in JavaScript/jQuery so this might be a stupid question.
Thank you
$(document).on('change', getCheck);
function getCheck() {
var total= 0;
$('[type="checkbox"]:checked').not("#discount").each(function(i, el) {
//console.log($(this).not("#off").val());
var SumVehicle = parseFloat($(el).val());
total += SumVehicle;
//console.log(total);
//console.log(price_tot);
$('#rata').text(total +" €");
var finalprice = total;
//var Check = getCheck();
if(typeof(total) != "undefined" && total !== 0) {
$('[type="checkbox"]:checked').not(".sum").each(function(i, el) {
var Discount = parseFloat($(this).val());
finalprice = finalprice - Discount;
console.log(finalprice);
$('#rata').text(finalprice +" €");
});
};
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="sum" type="checkbox" name="vehicle1" value="1000"> I have a bike<br>
<input class="sum" type="checkbox" name="vehicle2" value="2000"> I have a car<br>
<br><br><br>
<input id="discount" type="checkbox" name="discount" value="200"> Discount<br>
<div id="rata">rata</div>
Replace your js code with this code. the error will be resolved.
$( document ).ready(function() {
$("input[type='checkbox']").on('change', getCheck);
});
function getCheck() {
var total= 0;
$('[type="checkbox"]:checked').not("#discount").each(function(i, el) {
console.log($(this).not("#off").val());
var SumVehicle = parseFloat($(el).val());
total += SumVehicle;
console.log(total);
//console.log(price_tot);
$('#rata').html(total +" €");
var finalprice = total;
var Check = function getCheck(){
if(typeof(Check) != "undefined" && Check !== null) {
$("#discount").toggle();
var Discount = parseFloat($(this).val());
finalprice -= Discount;
console.log(finalprice);
$('#rata').text(finalprice +" €");
};
};
});
};

get the sum of two checkbox on check

hy, my is that it doesn't work. i want on check to visualize the sum between the selected checkbox. for example if i check only the first, it shows me a value, for the other one another value; if i check both, the sum of the values.
thanks for the help
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function setvalue(x){
if(x.checked){
x.value = x.defaultValue;
} else {
x.classList.value = 0;
}
return x.value;
}
var a = setvalue(document.getElementById("checkvalnotset1"));
var b = setvalue(document.getElementById("checkvalnotset2"));
var p = document.getElementById("sumvalnotset");
function sumvalnotset(){
p.innerHTML = "the value is " + +a + +b
}
</script>
</div>
var sum = 0;
function sumvalnotset(event) {
if(event.checked) {
sum = sum + parseInt(event.value);
} else {
sum = sum > 0 ? sum - parseInt(event.value) : sum;
}
document.getElementById('sumvalnotset').innerText = 'the value is: '+ sum;
}
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset(this)" onchange=""> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset(this)"> this is a checkbox that gain value when checked
<p id="sumvalnotset">
the value is: 0
</p>
</div>
You could rewrite your event handler has follows:
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function sumvalnotset() {
var chk1 = document.getElementById("checkvalnotset1");
var chk2 = document.getElementById("checkvalnotset2");
var val1 = chk1.checked ? Number(chk1.value):0;
var val2 = chk2.checked ? Number(chk2.value):0;
var p = document.getElementById("sumvalnotset");
p.innerHTML = "the value is " + (val1 + val2);
}
</script>
</div>

How do I add a #.## value to a textbox that already has another ##.## value in it only if a checkbox is checked?

I have been trying to figure out how to make it so that if a specific checkbox is checked, the total amount in a textbox gets 50.00 added to it when the submit button is clicked, before it submits the form. In fact, it would be better to have the update happen as soon as the checkbox is checked.
Here's what i tried so far:
<!DOCTYPE html>
<html>
<head>
<script>
function toggle(){
var indoorCamping = 50.00;
var total = 0.00;
if(document.getElementByName('fifty').is(':checked')){
total = (indoorCamping + document.getElementsByName('Amount').value);
document.getElementsByName('Amount').value = total;
}
else{
return;
}
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<input type="checkbox" name="fifty" value="indoor"/>
<label for="Amount">Amount <span class="req">*</span> <span
id="constraint-300-label"></span></label><br />
<input type="text" class="cat_textbox" id="Amount" name="Amount" />
<p id="demo"></p>
<button onclick="toggle()">Click me</button>
</body>
</html>
The value of a text-input is always text (a string) initially. This value needs to be explicitly converted to a number before adding to it, otherwise it concatenates the text. So "20" would become "5020".
Borrowing mohkhan's code:
<script>
function toggle(checkbox){
var indoorCamping = 50.00;
var total = 0.00;
if(checkbox.checked){
total = (indoorCamping + document.getElementById('Amount').value * 1);
document.getElementById('Amount').value = total;
}
}
</script>
I've multipled by 1 which is one way to convert "20" to a number. Number(x), parseInt(x) and parseFloat(x) are other ways.
I would prefer to use an object variable though, amt:
<script>
function toggle(checkbox) {
var indoorCamping = 50.00;
var total = 0.00;
var amt = null;
if (checkbox.checked) {
amt = document.getElementById('Amount');
total = (indoorCamping + amt.value * 1);
amt.value = total;
}
}
</script>
Add the click event on the checkbox then. Like this...
<input type="checkbox" name="fifty" value="indoor" onclick="toggle(this);"/>
And then in your script...
<script>
function toggle(checkbox){
var indoorCamping = 50.00;
var total = 0.00;
if(checkbox.checked){
total = (indoorCamping + document.getElementById('Amount').value);
document.getElementById('Amount').value = total;
}
}
</script>

In JQuery, how do I add all the values of "checked" checkboxes together?

<input type="checkbox" class="new_message" value="1">
<input type="checkbox" class="new_message" value="2" checked="checked">
<input type="checkbox" class="new_message" value="4" checked="checked">
total_score = $("input.new_message").checked.each(function(){
...?
});
The total score should be 6. I want to add all the checked values up of the same class.
you can do something like this
var total_score = function () {
var x = 0 ;
$("input.new_message:checked").each(function(){
x += Number($(this).val());
});
return x ;
}
DEMO
Start a counter, then increment it on each pass. $.each won't return anything.
var total_score = 0;
$("input.new_message:checked").each(function(){
total_score += parseInt($(this).val());
});
Something like this :
var total_score = 0;
$('input.new_message:checked').each(function(){
total_score += Number($(this).val());
});
var sum = 0;
$("input.new_message").each(function(){
if($(this).prop(checked)){
sum += $(this).val();
}
});

Categories

Resources