I have a Bootstrap modal with multiple forms in it. All the forms have an input field and checkbox. I try to run a function update_amounts_modal every time a change event takes place. This working when I change the input value but doesn't work when I check/uncheck the checkbox.
UPDATE I'VE CREATED A FIDDLE HERE
The function:
function update_amounts_modal(){
var sum = 0.0;
$('form').each(function() {
var qty = $(this).find('.qty input').val();
var price = $(this).find('.price input').val();
qty= parseInt(qty) || 0;
price= parseFloat(price) || 0;
var amount = (qty*price)
sum+=amount;
});
$('.total-modal').text('€'+sum.toFixed(2));
}
The change function:
update_amounts_modal();
$('form .qty').change(function(){
update_amounts_modal();
$('.total-modal').change();
});
HTML:
<form method="post" data-target="#modal" data-async="" action="action_url">
<div class="qty cell">
<input type="text" class="qty" value="1" name="quantity">
</div>
<div class="price cell">
<span class="euro">€</span><input type="text" disabled="" class="price" value="0.60">
</div>
<div class="checkbox cell">
<input type="checkbox" checked="" value="12933006" name="product[]" class="idRow">
</div>
</form>
//And more forms exactly like this but with different input values!
<div class="total-modal">€0.00</div>
What actually needs to happen is that by checking/unchecking the value needs to be recalculated with the function. So if you have set qty to 10 and you uncheck the checkbox then this amount (10x eg. €0.25) must be deducted from the total.
I thought something like this should work but that isn't:
$(".idRow").change(function(){
if($(this).attr("checked")){
update_amounts_modal();
}
else{
update_amounts_modal();
}
I don't get an error there's just nothing happening. Is there a better way to accomplish this?
I'm not sure figure out your question correctly or not but i think you are looking for something like this:
function update_amounts_modal() {
var sum = 0.0;
$('form').each(function () {
var qty = $(this).find('.qty').val();
var price = $(this).find('.price').val();
var isChecked = $(this).find('.idRow').prop("checked");
if (isChecked){
qty = parseInt(qty, 10) || 0;
price = parseFloat(price) || 0;
var amount = (qty * price);
sum += amount;
}
});
$('.total-modal').text('€' + sum.toFixed(2));
}
$().ready(function () {
update_amounts_modal();
$('form .qty, form .idRow').change(function () {
update_amounts_modal();
});
});
Check JSFiddle Demo
Update:
If in some forms you don't have a CheckBox (in other words some prices aren't optional) so you have to check that CheckBox exist or not and if exist, so check that is checked or not.
in order to do that, modify the update function like this:
function update_amounts_modal() {
var sum = 0.0;
$('form').each(function () {
var qty = $(this).find('.qty').val();
var price = $(this).find('.price').val();
var checkbox = $(this).find('.idRow');
if (checkbox.prop("checked") || checkbox.length == 0){
qty = parseInt(qty, 10) || 0;
price = parseFloat(price) || 0;
var amount = (qty * price);
sum += amount;
}
});
$('.total-modal').text('€' + sum.toFixed(2));
}
in this line: if (checkbox.prop("checked") || checkbox.length == 0){ we say that sum the value if checkbox is checked (checkbox.prop("checked")) or there is no CheckBox (checkbox.length == 0).
Check JSFiddle Demo
Try this : Instead of attr use prop
$(".idRow").change(function(){
if($(this).prop("checked")){
update_amounts_modal();
}
else{
update_amounts_modal();
}
});
u can do
<div class="checkbox cell">
<input type="checkbox"/>
</div>
jQuery("div.checkbox > input:checkbox").on('click',function(){
alert('asdasd');
});
http://jsfiddle.net/1r7rk21w/
If you expect the values to update based on the checked property, then your sum function needs to actually use that check box right?
JS:
$('form').each(function () {
if ($(this).find(".idRow").prop("checked") === true){
//
// The normal computations you had before...
//
}
});
Related
I have multiple input type="number" on my page. They are dinamically generated each time a user clicks on a "add-form-row" button. I want to give as value to a h2 element in my DOM based on the sum of each of these input each time a new input is added. When I try to sum the inputs, though, a NaN is returned. How can I fix this?
$(document).on('click', '.add-form-row', function(e){
e.preventDefault();
//cloneMore('.form-row:last', 'elements');
// here starts the sum logic
var tot = 0;
currentTotal = $('.form-row').find('input[type=number]').each(function() {
numberPrice = parseInt($(this).val())
tot += numberPrice
});
$('.totalPrice').text(`<span>${tot}</span>`)
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<input type="number" value="1">
<input type="number" value="2">
<button class="add-form-row">add</button>
<div class="totalPrice"></div>
</div>
If any of the input value is ="", i.e nothing, the total will be NaN, because parseInt("") = NaN, so maybe adding a condition like this can solve your problem:
$(document).on('click', '.add-form-row', function(e){
e.preventDefault();
//cloneMore('.form-row:last', 'elements');
// here starts the sum logic
var tot = 0;
currentTotal = $('.form-row').find('input[type=number]').each(function() {
if($(this).val() != ""){
numberPrice = parseInt($(this).val());
tot += numberPrice;
}
});
$('.totalPrice').text(`<span>${tot}</span>`);
return false;
});
I have this function for my computation that whenever the text fields are populated, it will add a stack to a variable and whenever a checkbox is checked on the text field, the text field wont add a value.
everything is working except the checkbox function, I already tried onchange and onclick but nothing happens. Can you check my codes?
Script:
function submission(){
x = 19;
ctr = 1;
ctr2 = 0;
days = ('<?php echo $query[0]->totaldays; ?>') - 1;
$('#payment').html('');
for(i = 1; i<=x ; i++){
if($('#guest'+i).val() != ""){
ctr++;
}
if(document.getElementById('kid'+i).checked){
ctr2++;
}
}
totalCount = 0;
totalCount = parseInt(ctr) - parseInt(ctr2);
totalCount = parseInt(ctr) * parseInt(days);
totalCount = parseFloat(totalCount) * 100;
$('#totalPayment').val(totalCount);
$('#payment').html(totalCount);
}
HTML:
<div class="row">
<div class="col-sm-10">
<label for="exampleInputtext1"><a style = "color:black; font-size: 10px;" ><input onchange="submission()" type="checkbox" name="kid1" id="kid1" > </a>Guest 1:</label>
<input type="text" class="form-control" onblur="submission()" name="guest1" id="guest1"/>
</div>
</div>
The onclick event handler will work for checkbox,you can try this code,
HTML:
<input onclick="submission(this)" type="checkbox" name="kid1" id="kid1" >
JS:
And you can check and see whether the checkbox is checked or not using the following code,
function submission(click){
....
var clicked=click.checked;
...
}
if it is true that means the checkbox has been checked and if it is false it has not been checked.
$("#guest1").change(function() {
if(this.checked) {
//Do this.
}
else{
// Do this.
}});
don't need to mention onclick function on html. just add this code in JS.
its calling auto based on id.
let me know if you need any help in understanding.
Ajay
thanks for your answers, it seems like I just messed up a little bit on my mathematical equation.
totalCount = 0;
totalCount = parseInt(ctr) - parseInt(ctr2);
totalCount = parseFloat(totalCount) * parseInt(days);
totalCount = parseFloat(totalCount) * 100;
$('#totalPayment').val(totalCount);
$('#payment').html(totalCount);
What I need is when the updateTotal function triggers (by checking or unchecking the checkbox), it loops the itemprice column and adds it to the totalPrice variable if its corresponding checkbox located in tditem column is checked. Otherwise, don't add the itemprice's value to totalPrice.
<table id="tblItem">
<body>
<tr>
<td class="hidden" id="tditemid"></td>
<td id="tditem">
<input type="checkbox" id="chckItemId" name="selectedItems" checked="checked" onclick="updateTotal(this)" />
<label id="lblitem"></label>
</td>
<td id="itemprice"></td>
<td class="hidden" id="tdstatus"></td>
</tr>
</body>
</table>
<input class="form-control input-sm" id="total" name="totalprice" readonly="true" type="text" value="">
Javascript
//Update total textbox when checkbox is checked/unchecked
window.updateTotal = function (element) {
var totalPrice = 0.00;
//Get clicked dropdown row and col id
var chckRow = element.parentNode.parentNode.rowIndex;
var chckCol = element.parentNode.cellIndex;
//What to do??
//Display total price
$('#totalprice').val(totalPrice);
}
Look on the code bellow
var totalPrice = 0;
window.updateTotal = function (element) {
var jqEl = $(element);
var isChecked = jqEl.prop('checked') === true;
totalPrice = isChecked ? totalPrice += parseInt(jqEl.attr('data-price')) : totalPrice -= parseInt(jqEl.attr('data-price'));
$('#total').val(totalPrice);
}
function init () {
var elements = $('input[name="selectedItems"]');
elements.each(function (index, item) {
var element = $(item);
var isChecked = element.prop('checked');
totalPrice = isChecked ? totalPrice += parseInt(element.attr('data-price')) : totalPrice;
});
$('#total').val(totalPrice);
};
init();
You need to create totalPrice variable. Next i create a data-price attribute for better working with HTML DOM elements. There you no need to use something like element.parent. .... because this is not good approach. init function is like your constructor and will be executed at the start of the app or what is it.
Here is your JSfiddle
You can just select the checked inputs and then calculate the total based on their parent's sibling .itemprice element "value".
Also since you can only have one #id you can use a class for .itemprice which can be present for multiple elements.
//Update total textbox when checkbox is checked/unchecked
window.updateTotal = function (element) {
var totalPrice = 0.00;
$("input:checked").each(function(){
totalPrice += parseFloat($(this).parent().next('.itemprice').text());
});
$('#totalprice').val(totalPrice);
}
DEMO
I have a global variable :
var a;
I put my onclick function into my html div in concatenation PHP :
$number =' <div onclick="select(this,'."'250000'".');" > ';
$number .= ...etc... //php function
$number .='</div>';
to insert string into div value onclick (button) :
function select (price){
if ($(id).attr('class') == "table2") { //unselect button
$(id).attr('class', 'table1');
var price2=document.getElementById("price").value.split(",");
var removePrice = price;;
var price3 = jQuery.grep(price2, function (value) { return value != removePrice;});
document.getElementById("price").value = price3;
if (n.length == 0) i = 0;
} else {
$(id).attr('class', 'table2'); //select button
if (i == 0) {
document.getElementById("price").value = price;
a = Number(document.getElementById("price").value); //assign the value into a
i = 1;
} else {
$(id).attr('class','table3');
}
}
From there, I have checkbox HTML :
<div id="CourseMenu"><input type="checkbox" value="50000" />  Ekstra Bed <input type="checkbox" value="50000" />  Breakfast</div>
After that I have another function to sum 2 div value (checkbox) :
$(function($) {
var sum = 0;
$('#CourseMenu :checkbox').click(function() { sum = 0;
$('#CourseMenu :checkbox:checked').each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
var b = parseInt(a||0, 10) + parseInt(sum||0, 10);
$('#sum').html(b); //<--resulted NaN when sum with button
document.getElementById("price").value=b; //<-- assign b as div value
});
});
The purpose is to sum the total price (button & checkbox) into div value
<input type="hidden" id="price" name="price" value="" />
it works fine when the function sum only the checkbox, but when I try to show the sum with the button (global variable) it resulted in NaN
I think I already convert the string into number there, is there something wrong with my code?
I think you have a problem in passing the arguments in onclick event:
onclick="select(this,'250000');" => passing this as first argument try changing to onclick="select('250000')";
but your select function is expecting string as the first argument:
function select(price){ //<-- simplified
document.getElementById("price").value=price;
a = Number(document.getElementById("price").value);
}
Here is an actual solution for your X/Y problem.
The code will initialise the field and clicking buttons or checking checkboxes work independently.
function calc() {
var sum = parseInt($("#price").text(), 10);
$('#CourseMenu :checkbox:checked').each(function() {
sum += parseInt(this.value, 10);
});
$('#sum').val(sum);
}
$(function() {
$("#CourseMenu .btn").on("click", function() {
$("#price").text($(this).data("price")); // using the data attribute
calc();
});
$('#CourseMenu input:checkbox').on("click",function() {
calc(); //
});
calc(); // initialise in case the page is reloaded.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="CourseMenu">
<button type="button" class="btn" data-price="25000">25000</button>
<button type="button" class="btn" data-price="35000">35000</button>
<div id="price">0</div>
<br/>
<label>
<input type="checkbox" value="200" />200</label>
<label>
<input type="checkbox" value="300" />300</label>
<label>
<input type="checkbox" value="400" />400</label>
<br/>
<input type="text" id="sum" value="" />
</form>
PS: If you do nothing else on click of checkboxes, you can write
$('#CourseMenu input:checkbox').on("click",calc);
Does anyone have any ideas why the entered deposit value is not deducting from the total value here?
$(document).ready(function () {
$('#invoice_table').on('input', '.calculate', function () {
calculateTotal();
});
function calculateTotal() {
// calculate deposit
var total = parseInt($('#invoice_total').val()) || 0,
deposit = parseInt($('#invoice_deposit').val()) || 0;
var calcDeposit = total - deposit;
$('#invoice_total').val((calcDeposit).toFixed(2));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="invoice_table">
<input type="text" name="invoice_discount" id="invoice_discount" value="" class="calculate" />
<input type="text" name="invoice_total" id="invoice_total" value="1000" />
</div>
http://jsfiddle.net/fn6L2eqp/2/
I have created this Fiddle for you,
You were overwriting the value set in the invoice_total text box.
I have added a <span> to display the result instead.
This way you get the result you want.
I think you would want the js to be http://jsfiddle.net/fn6L2eqp/2/ :
$(document).ready(function() {
$('#invoice_table').on('change', '.calculate', function () {
calculateTotal();
});
function calculateTotal() {
// calculate deposit
var total = parseInt($('#invoice_total').val()) || 0,
deposit = parseInt($('#invoice_discount').val()) || 0;
var calcDeposit = total - deposit;
$('#invoice_total').val((calcDeposit).toFixed(2));
}
});