Wrong Result Calculate value with checkbox use Jquery - javascript

Now im doing some Calculate Checkbox Value Using JQuery and PHP code. The mechanism is, when User checked the checkbox, it will sum the price. I implemented a formula for JQuery but the result it not correct. here is my code
JQUERY
<script>
$(function() {
$('.dealprice').on('input', function(){
const getItemPrice = $(this).closest("tr").find('input[name=itemprice]').val();
var eachPrice = 0;
$('.dealprice:checkbox:checked').each(function(){
eachPrice += isNaN(parseInt(getItemPrice)) ? 0 : parseInt(getItemPrice);
});
$("#totalDeal").text(eachPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
});
</script>
for more detail. i made a sample on this site https://repl.it/#ferdinandgush/Sum-Calculate-checkbox just click "run" button and you can able to test it. i need to display correct calculate following that table format
Please help.

You just have to define getItemPrice inside the loop, otherwise you are calculating it only once for the item that was clicked, instead of doing it for every item.
$(function() {
$('.dealprice').on('input', function(){
var eachPrice = 0;
$('.dealprice:checkbox:checked').each(function(){
const getItemPrice = $(this).closest("tr").find('input[name=itemprice]').val();
eachPrice += isNaN(parseInt(getItemPrice)) ? 0 : parseInt(getItemPrice);
});
$("#totalDeal").text(eachPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
});
<table class="tg">
<thead>
<tr>
<th class="tg-qh0q">Item</th>
<th class="tg-qh0q">Price</th>
<th class="tg-qh0q">Deal</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tg-0lax">Book</td>
<td class="tg-0lax">$ 10 <input type="hidden" name="itemprice" value="10"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][0]"></td>
</tr>
<tr>
<td class="tg-0lax">Pencil</td>
<td class="tg-0lax">$ 5 <input type="hidden" name="itemprice" value="5"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][1]"></td>
</tr>
<tr>
<td class="tg-0lax">Pen</td>
<td class="tg-0lax">$ 8 <input type="hidden" name="itemprice" value="8"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][2]"></td>
</tr>
<tr>
<td class="tg-amwm" colspan="2">Total</td>
<td class="tg-0lax"><span id="totalDeal">0</span></td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You have to put the getItemPrice inside of the function of where you get its checked. Please check the following code:
$(function() {
$('.dealprice').on('input', function(){
var eachPrice = 0;
$('.dealprice:checkbox:checked').each(function(){
const getItemPrice = $(this).closest("tr").find('input[name=itemprice]').val();
eachPrice += isNaN(parseInt(getItemPrice)) ? 0 : parseInt(getItemPrice);
});
$("#totalDeal").text(eachPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
});
Also check this repl https://repl.it/repls/LavenderAgonizingRoot

Related

How to get value Check and Uncheck checkbox use JQuery on array

Now im doing PHP Project combine with JQuery. I want to get value from checkbox both checked and unchecked on array. here is what i try
$(function() {
$('.dealprice').on('input', function(){
if($('.dealprice:checkbox:checked').prop('checked')){
//CHECKED
console.log("Checked");
const getPrice = $(this).closest("tr").find('input[name=itemprice]').val();
console.log(getPrice);
}else{
//UNCHECKED
console.log("Uncheck");
const getPrice = $(this).closest("tr").find('input[name=itemprice]').val();
console.log(getPrice);
}
});
});
i make a sample on this site. https://repl.it/#ferdinandgush/get-value-checkbox please click "RUN" bottom on the top to able test it.
the problem is, when the checkbox checked more then 1 and when i want to uncheck 1 of it. it still return value "True" not "false".
what i want it. each of checkbox can return value wherever i checked and uncheck it.
checked return consolo.log('true');
unchecked return consolo.log('false');
please help
I believe you can just do it like this if ($(this).prop('checked')) {
Then it will only check if the checkbox that you click on is checked or not.
Demo
$(function() {
$('.dealprice').on('input', function() {
if ($(this).prop('checked')) {
//CHECKED
console.log("Checked");
const getPrice = $(this).closest("tr").find('input[name=itemprice]').val();
console.log(getPrice);
} else {
//UNCHECKED
console.log("Uncheck");
const getPrice = $(this).closest("tr").find('input[name=itemprice]').val();
console.log(getPrice);
}
});
});
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
overflow:hidden;padding:10px 5px;word-break:normal;}
.tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal;}
.tg .tg-qh0q{background-color:#c0c0c0;color:#000000;font-weight:bold;text-align:center;vertical-align:top}
.tg .tg-0lax{text-align:left;vertical-align:top}
.tg .tg-amwm{font-weight:bold;text-align:center;vertical-align:top}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tg">
<thead>
<tr>
<th class="tg-qh0q">Item</th>
<th class="tg-qh0q">Price</th>
<th class="tg-qh0q">Deal</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tg-0lax">Book</td>
<td class="tg-0lax">$ 10 <input type="hidden" name="itemprice" value="10"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][0]"></td>
</tr>
<tr>
<td class="tg-0lax">Pencil</td>
<td class="tg-0lax">$ 5 <input type="hidden" name="itemprice" value="5"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][1]"></td>
</tr>
<tr>
<td class="tg-0lax">Pen</td>
<td class="tg-0lax">$ 8 <input type="hidden" name="itemprice" value="8"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][2]"></td>
</tr>
<tr>
<td class="tg-0lax">spidol</td>
<td class="tg-0lax">$ 15 <input type="hidden" name="itemprice" value="15"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][3]"></td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function(){
$(".dealprice").change(function(){
if($(this).is(":checked")){
console.log(true);
} else {
console.log(false);
}
});
});
</script>

Dynamic table if checkbox is unchekd empty() the td cell with JS

I have dynamic table that in one td passes php vales of prices and on end of the table is sum of those prices. There is also a checkbox in every row default checked. I need to empty the content of row where checkbox is unchecked so it removes that price value out of sum calculation.
Question, will that even remove that value? I know setting the td field to hide does not.
Value cell:
<td style="width:10%" class="rowDataSd" id="value">
<?php echo
str_replace(array(".", ",",), array("", "."), $row['rad_iznos']);
?>
</td>
Checkbox cell:
<td style="width:3%">
<input class="w3-check" type="checkbox" checked="checked" id="remove" name="uvrsti" value="<?php echo $row['rad_id']?>">
</td>
I tried with this but nothing happens with no errors:
$(document).ready(function(){
if($("#remove").is(':checked')) {
$("#value").show();
} else {
$("#value").empty();
}
});
I can pass the unique values into each checkbox and value element into id's like:
id="<?php echo $row['rad_id']?>"
. So they tie each other but don't know how to say in JS to empty those elements.
I was also thinking something along the lines of, if on some row checkbox is unchecked empty closest td with id="value". My guess is that would be best solution but I don't know how to write it.
Or even if checkbox is unchecked remove css class .rowDataSd to closest td with id="vale" based on whom calculation is made.
Sum script:
var totals=[0,0,0];
$(document).ready(function(){
var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.rowDataSd').each(function(i){
totals[i]+=parseFloat( $(this).html());
});
});
$("#sum_table td.totalCol").each(function(i){
$(this).html('<span style="font-weight: bold;text-shadow: 0.5px 0 #888888;">'+totals[i].toFixed(2)+' kn</span>');
});
});
As seen on picture need to remove row out of calculation if checkbox is unchecked. Keep in mind I dont want to delete to row, just remove it our of calculation.
Any help with how to approach this is appreciated.
Here is a basic example.
$(function() {
function getPrice(row) {
var txt = $(".price", row).text().slice(1);
var p = parseFloat(txt);
return p;
}
function calcSum(t) {
var result = 0.00;
$("tbody tr", t).each(function(i, r) {
if ($("input", r).is(":checked")) {
result += getPrice(r);
}
});
return result;
}
function updateSum(tbl) {
var t = calcSum(tbl);
$("tfoot .total.price", tbl).html("$" + t.toFixed(2));
}
updateSum($("#price-list"));
$("#price-list input").change(function() {
updateSum($("#price-list"));
});
});
#price-list {
width: 240px;
}
#price-list thead th {
width: 33%;
border-bottom: 1px solid #ccc;
}
#price-list tfoot td {
border-top: 1px solid #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="price-list">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr>
<td class="item name">Item 1</td>
<td class="item price">$3.00</td>
<td><input type="checkbox" checked /></td>
</tr>
<tr>
<td class="item name">Item 2</td>
<td class="item price">$4.00</td>
<td><input type="checkbox" checked /></td>
</tr>
<tr>
<td class="item name">Item 3</td>
<td class="item price">$5.00</td>
<td><input type="checkbox" checked /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td class="total price">$0.00</td>
<td> </td>
</tr>
</tfoot>
</table>
It all boils down to setting up an event handler for the checkboxes. The event handler should perform the following:
Track the checkbox change event for all checkboxes and the DOM ready event
Calculate the total of all rows with checkbox checked
Set the total to the total element
It call also perform any desired changes on the unchecked row .. not done in sample code below
THE CODE
$(function() {
$('.select').on('change', function() {
let total = $('.select:checked').map(function() {
return +$(this).parent().prev().text();
})
.get()
.reduce(function(sum, price) {
return sum + price;
});
$('#total').text( total );
})
.change();//trigger the change event on DOM ready
});
THE SNIPPET
$(function() {
$('.select').on('change', function() {
let total = $('.select:checked').map(function() {
return +$(this).parent().prev().text();
})
.get()
.reduce(function(sum, price) {
return sum + price;
});
$('#total').text( total );
})
.change();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr>
<td>Item 1</td>
<td>1000</td>
<td><input type="checkbox" class="select" checked></td>
</tr>
<tr>
<td>Item 2</td>
<td>1200</td>
<td><input type="checkbox" class="select" checked></td>
</tr>
<tr>
<td>Item 3</td>
<td>800</td>
<td><input type="checkbox" class="select" checked></td>
</tr>
<tr>
<td>Item 4</td>
<td>102000</td>
<td><input type="checkbox" class="select" checked></td>
</tr>
</tbody>
</table>
<span>TOTAL</span><span id="total"></span>

How to get multiple selected cell array values with checkbox in jquery, then send with ajax post

How should I get an array value from a table cell when clicking checkbox with jQuery? If I've selected cell 1, I want to get array like ["BlackBerry Bold", "2/5", "UK"], but if I've selected all of them, I want to get all the data in the form of an array of arrays.
<table border="1">
<tr>
<th><input type="checkbox" /></th>
<th>Cell phone</th>
<th>Rating</th>
<th>Location</th>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
<td>UK</td>
</tr>
<tr>
<td align="center"><input type="checkbox" /></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
<td>US</td>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>Droid X</td>
<td>4.5/5</td>
<td>REB</td>
</tr>
Please help.
Onclick get 3 children of the parent and add content to data. Used jquery nextAll for siblings and splice the 3 required.
Attached event to the table, onclick will check if element is INPUT.
If it's input, will get parent of that input which will be <td>.
For this parent element, will get three siblings using jquery.
Will add in selected if not present else delete, using indexOf.
CodePen for you to playaround: [ https://codepen.io/vivekamin/pen/oQMeXV ]
let selectedData = []
let para = document.getElementById("selectedData");
let tableElem = document.getElementById("table");
tableElem.addEventListener("click", function(e) {
if(e.target.tagName === 'INPUT' ){
let parent = e.target.parentNode;
let data = [];
$(parent).nextAll().map(function(index, node){
data.push(node.textContent);
})
let index = selectedData.indexOf(JSON.stringify(data))
if(index == -1){
selectedData.push(JSON.stringify(data));
}
else{
selectedData.splice(index,1);
}
para.textContent = "";
para.innerHTML = selectedData ;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" id="table">
<tr>
<th><input type="checkbox" /></th>
<th>Cell phone</th>
<th>Rating</th>
<th>Location</th>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
<td>UK</td>
</tr>
<tr>
<td align="center"><input type="checkbox" /></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
<td>US</td>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>Droid X</td>
<td>4.5/5</td>
<td>REB</td>
</tr>
</table>
<h3> Selected Data: </h3>
<p id="selectedData"></p>
Updated to meet your needs.
create a function to build the array values based on looking for any checked inputs then going to their parents and grabbing the sibling text values
attach your change event to the checkbox click even.
I provided a fiddle below that will output the array in the console.
function buildTheArray(){
var thearray = [];
$("input:checked").parent().siblings().each(function(){
thearray.push($(this).text());
});
return thearray;
}
$("input[type='checkbox']").change(function(){
console.log(buildTheArray());
});
Fiddle:
http://jsfiddle.net/gcu4L5p6/

getting the value of a check box

Ok, I am running a javascript that is testing a bunch of to see if they are changed, and if they are changed, I need to see if a check box is checked. I am not using a form to do this, however, for certain reasons. Here is the code for the display of the table:
<table class="db-view-sku-table">
<thead>
<tr>
<th>Merge <br />Callouts</th>
<th>Current Page</th>
<th>Current Callout</th>
<th>New Page</th>
<th>New Callout</th>
<th>MFG SKU</th>
<th>Client SKU</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="odd changed_value">
<td class="hidden db-sku-nid">192297</td>
<td class="hidden db-co-nid">212300</td>
<td class="merge"><input type="checkbox" name = "mergeme" class="checked" /></td>
<td class="db-current-page">6</td>
<td class="db-current-co">A</td>
<td class="db-move-page"><input type="text" class="page-select" size="4" value="" /></td>
<td class="db-move-co"><input type="text" class="co-select" size="4" value="A" /></td>
<td class="db-sku">AAG794200</td>
<td class="db-client-sku editable-text">AAG-794200</td>
<td class="db-description">AT-A-GLANCE Sorbet Wkl/Mthly Plnr</td>
</tr>
<tr class="even changed_value">
<td class="hidden db-sku-nid">97160</td>
<td class="hidden db-co-nid">212301</td>
<td class="merge"><input type="checkbox" name = "mergeme" class="checked" /></td>
<td class="db-current-page">6</td>
<td class="db-current-co">A</td>
<td class="db-move-page"><input type="text" class="page-select" size="4" value="" /></td>
<td class="db-move-co"><input type="text" class="co-select" size="4" value="A" /></td>
<td class="db-sku">AAG76PN0105</td>
<td class="db-client-sku editable-text">AAG-76PN0105</td>
<td class="db-description">QUICKNOTES WKLY/MNTH, SPECIAL EDITION</td>
Code when save button is pushed:
function setupMassSave() {
$('.save-button').click(function() {
var merge = getMergeList();
var skus = getSkuList();
var pages = getPageList();
var callouts = getCalloutList();
var currco = getCurrCalloutList();
$.ajax({
url: '/skumove/save_all/' + merge + '/' + skus + '/' + pages + '/' + callouts + '/' + currco,
cache: false,
success: refreshView
});
});
}
function getSkuList() {
var slist = [];
$('.changed_value').each(function(index) {
if(!$(this).children('.merge').children('.checked').checked){
slist.push($(this).children('.db-sku-nid').text());
}
});
return slist;
}
function getMergeList() {
var mlist = [];
$('.changed_value').each(function(index) {
if($(this).children('.merge').children('.checked').checked) {
mlist.push($(this).children('.db-sku-nid').text());
}
});
return mlist;
}
The only ones I'm having a problem with are those two functions. They other 3 functions work fine and return the values I need. I know the problem is somewhere within the ('.merge').clicked area.
Thanks for your help.
.checked is a (Boolean) vanilla JavaScript property, which you're trying to apply to a jQuery object. That's why it's not working.
Replace
$(this).children('.merge').children('.checked').checked
with either
$(this).children('.merge').children('.checked')[0].checked
or
$(this).children('.merge').children('.checked').is(':checked')
or
$(this).children('.merge').children('.checked:checked').length
use the pseudo selector :checked instead of the class selector .checked
if($(this).children('.merge').children(':checked').length) {
mlist.push($(this).children('.db-sku-nid').text());
}

Not getting the value from a div in JavaScript

I am trying to calculate amount without VAT from a pre-calculated amount with VAT . The HTML form looks like :
<table>
<tr>
<th>Sl No</th>
<th>Description of goods</th>
<th>Price</th>
<th>VAT%</th>
<th>Price with VAT</th>
<th>Quantity</th>
<th>Amount</th>
</tr>
{foreach name = feach item = k from = $ip key = ind}
<tr>
<td>{$ind+1}</td>
<td>{$k->brand},{$k->model}</td>
<td id="prd_prc"> </td>
<td id="vat{$ind}">
<select name="vatpc" id="vatpc" onchange="calculate('{$ind}')">
<option value="5">5</option>
<option value="13.5">13.5</option>
</select>
</td>
<td id="total_cost{$ind}">{$k->price}</td>
<td>{$k->quantity}</td>
<td>{$k->total_cost}</td>
</tr>
{/foreach}
<tr>
<td> </td>
<td> </td>
<td> </td>
<td>Total Cost </td>
<td>{$final_amount}</td>
</tr>
</table>
And the JavaScript function is :
function calculate(idno)
{
//alert(idno);
var vat_pc = document.getElementById("vatpc").value;
var total_cost = document.getElementById("total_cost"+idno).value;
//total_cost = Number(total_cost);
alert(total_cost);
//vat_pc = parseFloat(vat_pc);
// = v + 2.10 + 11.25;
//alert(v);
// document.getElementById("total").innerHTML = "Total - amount : "+v+" USD";
}
But the alert shows undefined. I tried adding innerHTML,but results same. Please help. Thanks in advance
total_costX is a <td> element. Use the textContent property.
var total_cost = document.getElementById("total_cost"+idno).textContent;
There in nothing like value of dive. But you can get text or html inside dive. if you are using jquery, it should be quite simple:
$(document.getElementById("vatpc")).text();
//OR
$(document.getElementById("vatpc")).html();
Or jQuery's way
$("#vatpc").text();
//OR
$("#vatpc").html();

Categories

Resources