How to bring only price value which with text and curreny symbol? - javascript

Now I have NT$ symbol in price, so i want to remove it so i can bring the only price(number) into script to future calculate.
what should I change?
var test = document.querySelector(".origprice");
var price = parseInt(fparent.textContent.replace(/NT/,/\U+00024/,/,/,''));
var testt = price - 150;
document.getElementById("demo").innerHTML = testt;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="test">
<table id="table">
<tr>
<td class="origprice">NT$ 1,500</td>
</tr>
</table>
<p id="demo"></p>
</div>

you can use this function to get the desired result.
var txt="NT$ 1,500";
let t= ""
var numb = txt.match(/\d/g).map(i => {
t += i ;
})
console.log(+t);

If you will have space between prices and $, then you can do like the below,
$(document).ready(function(){
let total = 0;
$('.origprice').each(function() {
total += Number($(this).text().split(' ')[1]);
});
console.log(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="origprice">NS$ 10000</td>
<td class="origprice">NS$ 20000</td>
<td class="origprice">NS$ 30000</td>
</tr>
</table>

Related

Get summary number from only visible table rows

I have a code which counts a total summary of all price table cells. This is not exactly what do I need. I need to count the summary from only visible rows. I use filtering by date range, once I change date it displays only dates from the selected date range, but the summary price is from the all rows. I need to implement the part of the code for visible table rows only and update the summary price in the span.
Any advice?
function filterRows() {
var from = jQuery("#datefilterfrom").val();
var to = jQuery("#datefilterto").val();
if (!from && !to) { // no value for from and to
return;
}
from = from || "1970-01-01"; // default from to a old date if it is not set
to = to || "2999-12-31";
var dateFrom = moment(from);
var dateTo = moment(to);
jQuery("#table tr").each(function(i, tr) {
var val = jQuery(tr).find("td:nth-child(2)").text();
var dateVal = moment(val, "DD.MM.YYYY");
var visible = (dateVal.isBetween(dateFrom, dateTo, null, [])) ? "" : "none"; // [] for inclusive
jQuery(tr).css("display", visible);
//summary start
var table = document.getElementById("table"),
sumVal = 0;
for (var i = 1; i < table.rows.length; i++) {
sumVal = sumVal + parseInt(table.rows[i].cells[2].innerHTML);
}
document.getElementById("val").innerHTML = "Sum Value = " + sumVal;
console.log(sumVal);
});
//summary end
}
jQuery("#datefilterfrom").on("change", filterRows);
jQuery("#datefilterto").on("change", filterRows);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<div class="row">
<div class="col-md-3">
<h4>Date from</h4>
<input type="date" class="form-control" id="datefilterfrom" data-date-split-input="true">
<h4>Date to</h4>
<input type="date" class="form-control" id="datefilterto" data-date-split-input="true">
</div>
</div>
<span id="val"></span>
<table id="table" class="sortable">
<tr>
<th>Name</th>
<th>Date</th>
<th>Price</th>
</tr>
<tr>
<td>Name</td>
<td>20.10.2020</td>
<td>20</td>
</tr>
<tr>
<td>Name</td>
<td>21.10.2020</td>
<td>25</td>
</tr>
<tr>
<td>Name</td>
<td>22.10.2020</td>
<td>30</td>
</tr>
</table>
This is how it looks like when I select date range in HTML (so I need to get summary from only this selected tr)
I think there need to be some condition added here
sumVal = sumVal + parseInt(table.rows[i].cells[2].innerHTML);
You don't need two loops. You're already looping through the rows with .each() to make them visible or invisible, you can calculate the total in that same loop. After you determine if the row should be visible, use that variable in an if statement to add to the total.
jQuery has a built-in function .toggle() that will switch the visibility of an element. You can make visible a boolean variable instead of a display style value, then use that as the argument to .toggle(). Then you can use this same value in the if condition.
Make your access to columns less dependent on the table layout by using classes instead of column indexes. Use jQuery(tr).find(".price") to access the price column, for instance.
Use <thead> and <tbody> to distinguish the headings from the table data, then use tbody in the .each() loop to only process data rows.
function filterRows() {
var from = jQuery("#datefilterfrom").val();
var to = jQuery("#datefilterto").val();
if (!from && !to) { // no value for from and to
return;
}
from = from || "1970-01-01"; // default from to a old date if it is not set
to = to || "2999-12-31";
var dateFrom = moment(from);
var dateTo = moment(to);
var sumVal = 0;
jQuery("#table tbody tr").each(function(i, tr) {
var val = jQuery(tr).find(".date").text();
var dateVal = moment(val, "DD.MM.YYYY");
var visible = (dateVal.isBetween(dateFrom, dateTo, null, []));
jQuery(tr).toggle(visible);
if (visible) {
sumVal += parseInt(jQuery(tr).find(".price").text());
}
$("#val").text("Sum Value = " + sumVal);
});
}
jQuery("#datefilterfrom, #datefilterto").on("change", filterRows);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<div class="row">
<div class="col-md-3">
<h4>Date from</h4>
<input type="date" class="form-control" id="datefilterfrom" data-date-split-input="true">
<h4>Date to</h4>
<input type="date" class="form-control" id="datefilterto" data-date-split-input="true">
</div>
</div>
<span id="val"></span>
<table id="table" class="sortable">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Price</th>
</tr>
<thead>
<tbody>
<tr>
<td>Name</td>
<td class="date">20.10.2020</td>
<td class="price">20</td>
</tr>
<tr>
<td>Name</td>
<td class="date">21.10.2020</td>
<td class="price">25</td>
</tr>
<tr>
<td>Name</td>
<td class="date">22.10.2020</td>
<td class="price">30</td>
</tr>
<tbody>
</table>

Sum up cell values in HTML table if checkbox is checked

I have a table with three columns: item, price and a checkbox. I want to calculate the subtotal but only include the prices with a checked checkbox. The code I have so far is a mix of various bits that work on its own; however right now I get the error message "TypeError: Cannot read properties of undefined (reading 'innerHTML')". What am I doing wrong?
function calculate() {
const ele = document.getElementsByTagName('input');
let table = document.getElementById("myTable");
let tr = table.getElementsByTagName("tr");
let subTotal = 0;
for (var i = 0; i < ele.length; i++) {
let td = tr[i].getElementsByTagName("td")[1];
let price = td[i].innerHTML;
if (ele[i].type == 'checkbox' && ele[i].checked == true)
subTotal += price;
}
document.getElementById("val").innerHTML = "The subtotal is " + subTotal;
}
<!DOCTYPE html>
<html>
<body>
<table id="myTable">
<tr>
<td>T-Shirt</td>
<td>9.99</td>
<td><input type="checkbox"></td>
</tr>
<tr>
<td>Pants</td>
<td>49.99</td>
<td><input type="checkbox"></td>
</tr>
</table>
<span id="val">The subtotal is 0</span>
<button onclick="calculate()">Calculate subtotal</button>
</html>
You have to change the line td[i] because it's not defined as the error suggests. So, consider using bare td and accessing its innerText. It'll return a string with the value, which you have to convert to a float number with parseFloat. Finally, you must set the precision you want to subTotal so that it will print with the number of decimals you want.
function calculate() {
const ele = document.getElementsByTagName('input');
let table = document.getElementById("myTable");
let tr = table.getElementsByTagName("tr");
let subTotal = 0;
for (var i = 0; i < ele.length; i++) {
let td = tr[i].getElementsByTagName("td")[1];
let price = parseFloat(td.innerText); // change here
if (ele[i].type == 'checkbox' && ele[i].checked == true)
subTotal += price;
}
document.getElementById("val").innerHTML = "The subtotal is " + subTotal.toFixed(2); // and set precision here
}
<!DOCTYPE html>
<html>
<body>
<table id="myTable">
<tr>
<td>T-Shirt</td>
<td>9.99</td>
<td><input type="checkbox"></td>
</tr>
<tr>
<td>Pants</td>
<td>49.99</td>
<td><input type="checkbox"></td>
</tr>
</table>
<span id="val">The subtotal is: </span>
<button onclick="calculate()">Calculate subtotal</button>
</html>
Problem with your code is simple. You referenced the td and than you try to reference it again.
let td = tr[i].getElementsByTagName("td")[1];
let price = td[i].innerHTML;
Should be
const td = tr[i].getElementsByTagName("td")[1];
const price = td.innerHTML;
If you use a value on the checkbox, you can just loop over the checked inputs and calculate the total using the values. No need to look up cell contents.
function calculate() {
const checkedInputs = document.querySelectorAll("#myTable input:checked");
const total = Array.from(checkedInputs).reduce(function(total, cb) {
return total + +cb.value;
}, 0);
document.querySelector("#val").textContent = "The subtotal is " + total.toFixed(2);
}
<table id="myTable">
<tr>
<td>T-Shirt</td>
<td>9.99</td>
<td><input type="checkbox" value="9.99"></td>
</tr>
<tr>
<td>Pants</td>
<td>49.99</td>
<td><input type="checkbox" value="49.99"></td>
</tr>
</table>
<span id="val">The subtotal is 0</span>
<button onclick="calculate()">Calculate subtotal</button>
You can iterate trhough checkbox and going up until the previous td
function calculate() {
let chckboxes = document.querySelectorAll('#myTable input:checked');
let sum = 0;
chckboxes.forEach((itm) => {
let val = parseFloat(itm.parentElement.previousElementSibling.innerHTML)
sum += val;
});
document.getElementById("val").innerHTML = "The subtotal is " + sum;
}
<!DOCTYPE html>
<html>
<body>
<table id="myTable">
<tr>
<td>T-Shirt</td>
<td>9.99</td>
<td><input type="checkbox"></td>
</tr>
<tr>
<td>Pants</td>
<td>49.99</td>
<td><input type="checkbox"></td>
</tr>
</table>
<span id="val">The subtotal is 0</span>
<button onclick="javascript:calculate()">Calculate subtotal</button>
</html>

How to select the closest element with contains selector jquery

I want to replace the "{{my_name}}" and "{{my_email}}" with a string, but the program is not working, what should i do?
Thanks.
$(".notes *:contains('{{')").text(function() {
var rawkey = $(this).text().match(/{{(.*?)}}/i)[0]; // Output (console.log) : {{my_name}} or {{my_email}}
var key = $(this).text().match(/{{(.*?)}}/i)[1]; // Output (console.log) : my_name or my_email
if (key.indexOf('name') > -1) {
$(this).text($(this).text().replace(rawkey, "Tony"));
} else if (key.indexOf('email') > -1) {
$(this).text($(this).text().replace(rawkey, "tonyhawk#gmail.com"));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="notes">
<h4>{{my_name}}</h4>
<table>
<tr>
<td>
<p>{{my_name}}, {{my_email}}</p>
</td>
</tr>
</table>
</div>
Set the result after replacing back to the element's textContent:
$(".notes *:contains('{{')").text(function() {
var rawkey = $(this).text().match(/{{(.*?)}}/i)[0];
var key = $(this).text().match(/{{(.*?)}}/i)[1];
if (key.indexOf('name') > -1) {
$(this).text($(this).text().replace(rawkey, "Tony"));
} else if (key.indexOf('email') > -1) {
$(this).text($(this).text().replace(rawkey, "tonyhawk#gmail.com"));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="notes">
<h4>{{my_name}}</h4>
<table>
<tr>
<td>
<p>{{my_email}}</p>
</td>
</tr>
</table>
</div>
You can do like this.
var $content=$('.notes').html();
var finalContent=$content.replaceAll("my_name","Tony").replaceAll("my_email","tonyhawk#gmail.com").replaceAll("{{","").replaceAll("}}","");
$(".notes").html(finalContent);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="notes">
<h4>{{my_name}}</h4>
<table>
<tr>
<td>
<p>{{my_name}},{{my_email}}</p>
</td>
</tr>
</table>
</div>

Calculate sum of two dynamically created textboxes using jQuery

HTML:
<table id="tbl" border="1">
<tr>
<th>Name</th>
<th>Mark1</th>
<th>Mark2</th>
<th>Total</th>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text" class="cell"></td>
<td><input type="text" class="cell"></td>
<td><b><span id="total_sum_value"></span></b></td>
<td><b><span id="total_sum_value1"></span></b></td>
<th><input class="add-row" data-id="1" type="button" value="+"></th>
</tr>
</table>
JavaScript:
$(document).ready(function(){
var i = $(".add-row").data("id");
$(".add-row").click(function(){
$('#tbl').append('<tr><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td></tr>');
var two = $("input").addClass("cell"+i);
$("#tbl").on('input','.cell'+i,function(){
var sum1 = 0;
$(".cell"+i).each(function() {
var get_val = $(this).val();
sum1 += parseFloat(get_val);
});
$("#total_sum_value1").html(sum1);
});
i++;
});
$("#tbl").on('input','.cell',function(){
var sum = 0;
$('.cell').each(function(){
var get_val = $(this).val();
sum += parseFloat(get_val);
});
$("#total_sum_value").html(sum);
});
});
When you click on the plus sign button, it generates three textboxes. I want to calculate the sum of those textboxes and print it in a span.
Here is a CodePen of my code: https://codepen.io/anon/pen/XBqKVZ?editors=1010
can you try like this:
$('.cell').on('change', function(){
var sum = 0;
var data ={
}
$('.cell').each(function(index, item){
var val = $(item).val();
var get_val = $(this).val();
sum += Number(get_val);
console.log(sum);
});
$("#total_sum_value").html(sum);
});
URL: Jsfiddle

How to get input value using val() with js and jquery

I have been trying to take values of 4 inputs that are in a table and get the sum of the numbers on the input with a for loop but i keep getting 0 (the sum that i have defined)
Debugged everything and I am pretty sure the problem is in the "var x"- it just won't get any information from the inputs.
$(function () {
$("#inventoryForm").submit(function (event) {
var table = $("table")
var error = false;
event.preventDefault();
$(".inventoryInput").each(function(){
if($(this).val() < 0) {
error = true; //Indicate there was an error
$("#inventoryError").slideDown().text("Positive numbers only");
return false; //This stops the iteration
}
});
//Stop processing if there was an error
if (error) return;
if (!error) {
$("#inventoryError").hide();
}
$("#inventorySubmit").hide();
$("#inventoryChange").show();
$("#withdraw").show();
$(".inventoryInput").attr('disabled','disabled');
var sum = 0;
var money = table.find("td:nth-child(2)");
for (var i = 0; i<money.length; i++) {
var x = money.eq(i).val();
sum += x;
$("#totalMoney").text(sum);
}
console.log(money);
});
$("#inventoryChange").click(function () {
$("#inventorySubmit").show();
$("#inventoryChange").hide();
$("#withdraw").hide();
$(".inventoryInput").removeAttr('disabled');
});
});
.hidden {
display: none;
}
.error {
display: none;
color: red;
border: dotted 3px yellow;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>ATM</title>
<body>
<header>
<h1>Litman - Steklov ATMs</h1>
</header>
<section id="inventory">
<form id="inventoryForm">
<table>
<thead>
<tr>
<th>Bill</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>20</td>
<td>
<input id="inventoryInput" class="inventoryInput" type="number">
</td>
</tr>
<tr>
<td>50</td>
<td>
<input id="inventoryInput2" class="inventoryInput" type="number">
</td>
</tr>
<tr>
<td>100</td>
<td>
<input id="inventoryInput3" class="inventoryInput" type="number">
</td>
</tr>
<tr>
<td>200</td>
<td>
<input id="inventoryInput4" class="inventoryInput" type="number">
</td>
</tr>
</tbody>
</table>
<p id="inventoryError" class="error hidden">Validation errors will be here</p>
<p>Total Money: <span id="totalMoney"></span>
</p>
<button id="inventorySubmit" type="submit">Finish</button>
<button id="inventoryChange" type="button" class="hidden">Change</button>
</form>
</section>
<section id="withdraw" class="hidden">
<form>
<div>Withdraw:
<input type="number">
</div>
<p class="error hidden">Validation errors will be here</p>
<button type="submit">Process</button>
</form>
</section>
<section id="result" class="hidden">
<div>You Got:</div>
<button type="button">Finish</button>
</section>
</body>
</html>
The problem is indeed with
var x = money.eq(i).val();
money is an array of tds. So money.eq(i) is a td. What you want to get to is the actual input. So the solution is
var x = money.eq(i).find('input').val();
To elaborate on your further commend. If you fill in all 4 inputs using
var x = parseInt(money.eq(i).find('input').val());
it will sum them as expected. It will throw NaN when one of the inputs is empty because parseInt('') returns NaN, so you should check if the input actually has a value or not..
var input = money.eq(i).find('input').val();
var x = input ? parseInt(input) : 0
To further explain my code.
var input = money.eq(i).find('input').val();
This gets the value of the actual input, whatever that value may be.
var x = input ? parseInt(input) : 0
This checks whether the value of the input is empty or not. If it is empty then x=0 otherwise x=parseInt(input). So if the input is not empty, the value if being parsed to an int and assigned to x.
sum += x
x is being added to the final sum.

Categories

Resources