amount after ',' cannot be read - javascript

i have a js code that calculate the total amount when being click by checkbox. The user can either choose to select all or select only certain amount that they want to calculate. The function if the user 'select all'is work fine but when they click only certain amount that they want to calculate, if the amount is have ','in it, it will only take the number before the ','for example if the amount is 20,230, it will total the amount as 20.00. it work real fine if the number is only 20230 without the ','. help me please.
function checkedAll () {
var row_counter =0;
$("input[id ^= 'check_'] ").each(function() {
row_counter++;
});//en
var total=0;
for(var i=1; i<=row_counter; i++) {
//alert(i);
if (document.getElementById("checkall").checked==true){
document.getElementById('check_'+i).checked = true;
var amaun = document.getElementById('amaun_'+i).value;
//alert(amaun);
total = parseFloat(total)+parseFloat(amaun);
}
else{
document.getElementById('check_'+i).checked = false;
var amaun = 0;
total = parseFloat(total)+parseFloat(amaun);
}
}
document.getElementById("jum_baucar").value=total.toFixed(2);
}
function calcTotal(){
//alert("here");
var row_counter =0;
$("input[id ^= 'check_'] ").each(function() {
row_counter++;
});//en
var total=0;
for(var i=1; i<=row_counter; i++) {
//alert(i);
if (document.getElementById('check_'+i).checked == true){
var amaun = document.getElementById('amaun_'+i).value;
//alert(amaun);
total = parseFloat(total)+parseFloat(amaun);
}
else{
var amaun = 0;
total = parseFloat(total)+parseFloat(amaun);
}
}
document.getElementById("jum_baucar").value=total.toFixed(2);
}
Those are my js code.
what should I add into it?

Having a , in a number that is applied with parseFloat() treats it as a decimal. For example parseFloat('10,10') => 10. One simple solution is simply removing the , from the string:
amaun = amaun.replace(',',''); // Replace a comma with nothing
Or for several commas using a regexp to act as a "replaceAll()":
amaun = amaun.replace(RegExp(',','g'),'');
Then you can apply parseFloat(amaun):
total = parseFloat(total)+parseFloat(amaun);

Related

Why isn't querySelectorAll working with my ID values?

I use this piece of code for a live searching and for calculate the "Total" :
$('#search').keyup(function () {
var x = [];
var y = [];
var $total = 0;
var inputString = $("#search").val();
var act = document.getElementById("labdb").value;
$('td:first-child').parent().show();
$('td:first-child').parent().addClass("notHide");
$('td:first-child').parent().removeClass("toHide");
$var = $('td:first-child').parent('tr:not(:icontains(' + inputString + ')):not(:contains("Total"))');
$var.hide();
$var.addClass('toHide');
$var.removeClass('notHide')
for (var price of document.querySelectorAll('tr.notHide td.price')) {
x.push(parseFloat(price.innerText));
}
for (var cantidad of document.querySelectorAll('tr.notHide td.quantity')) {
y.push(parseFloat(cantidad.innerText));
}
for(var i = 0; i <= x.length-1; i++){
$total += x[i] * y[i];
}
document.getElementById("total"+act).innerText = $total.toFixed(2);
});
I have various tables, with differents ID's, first is id='0', second is id='1', etc.
I use collapse ('show') or ('hide') for show the selected table with a selector.
So, the problems comes when I try to calculate the "Total", It's calculated with the value of the class "notHide" and "price/quantity".
And all the tables get this Class, so the price got crazy if there is more than 1 table with "Total"
I KNOW, that I need to specify the ID of the table to work around, but I cant.
I have tested with:
var act = document.getElementById("labdb").value;
var actHTML = document.getElementById("labdb");
It get the ID from the selected table, and then, in this part of code include it:
for (var price of actHTML.document.querySelectorAll('tr.notHide td.price')) {
x.push(parseFloat(price.innerText));
}
for (var cantidad of actHTML.document.querySelectorAll('tr.notHide td.quantity')) {
y.push(parseFloat(cantidad.innerText));
}
But that, dont work, Im all the time thinking about other solutions and trying it, but I cant.
Its the final part of that page. Only need to specify the ID of the "Total" calculator.
I had tried to with:
for (var price of document.querySelectorAll('#'+act+' tr.notHide td.price')) {
x.push(parseFloat(price.innerText));
}
for (var cantidad of document.querySelectorAll('#'+act+' tr.notHide td.quantity')) {
y.push(parseFloat(cantidad.innerText));
}
For be more specific, I need that document.querySelectorAll('tr.notHide td.quantity') comes from a specific ID. For the rest, works perfectly, inclusive deleting the others tables with the parameter Total
EDIT_0:
I have do that:
let myTable = document.querySelector("#"+act);
let all = myTable.querySelectorAll('tr.notHide td.price');
for (var price of all) {
x.push(parseFloat(price.innerText));
}
for (var cantidad of all) {
y.push(parseFloat(cantidad.innerText));
}
for (var i = 0; i <= x.length - 1; i++) {
$total += x[i] * y[i];
}
from here: LINK
And that is the console error:
scripts.js:57 Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#0' is not a valid selector.
at changePrice (https://neutrino.ugr.es/js/scripts.js:57:28)
at HTMLSelectElement. (https://neutrino.ugr.es/js/scripts.js:15:5)
at HTMLSelectElement.dispatch (https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js:2:43336)
at y.handle (https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js:2:41320)
Well I found the error. The method document.querySelectorAll('') doesn't work if the ID starts with a digit. Like said in an article on the subject:
The spec defines identifiers using a token diagram. They may contain
the symbols from a to z, from A to Z, from 0 to 9, underscores (_),
hyphens -, non-ASCII symbols or escape sequences for any symbol.
They cannot start with a digit, or a hyphen (-) followed by a digit. Identifiers require at least one symbol (i.e. the empty
string is not a valid identifier).
This is the final code:
$('#search').keyup(function () {
var inputString = $("#search").val();
$('td:first-child').parent().show();
$('td:first-child').parent().addClass("notHide");
$('td:first-child').parent().removeClass("toHide");
$var = $('td:first-child').parent('tr:not(:icontains(' + inputString + ')):not(:contains("Total"))');
$var.hide();
$var.addClass('toHide');
$var.removeClass('notHide')
changePrice();
});
function changePrice() {
var x = [];
var y = [];
var $total = 0;
var act = document.getElementById("labdb").value;
actt="t"+act+act;
//alert(act);
var myTable = document.querySelector("#"+actt);
var allx = myTable.querySelectorAll('tr.notHide td.price');
var ally = myTable.querySelectorAll('tr.notHide td.quantity');
//alert(all)
for (var price of allx) {
x.push(parseFloat(price.innerText));
}
for (var cantidad of ally) {
y.push(parseFloat(cantidad.innerText));
}
for (var i = 0; i <= x.length - 1; i++) {
$total += x[i] * y[i];
}
//alert(x.length)
document.getElementById("total" + act).innerText = $total.toFixed(2);
}
I changed the ID to start with a t: actt="t"+act+act;
(act+act is because id is 00, not 0)

convert array.push.(prompt()) into a number

when i run the program the browser tell me moy is NaN yet I took care to use .map(Number) to convert the array into a number . I need some help please.
var score = [];
var i = 0;
var choice = 0;
while(choice != null){
i++;
score.push(prompt("put the score number "+i));
score = score.map(Number);
choice = prompt("to continue click on ok to cancel click on cancel");
}
var sum = 0,moy;
for(a=0;a<=i;a++) {
sum = sum+score[a];
moy = sum/i;
}
document.write("you put "+i+" score(s) <br>and the average is"+moy);
you have syntax error in this line
for(a=0;a<=i;a++) {
define a variable like this
for(var a=0;a<=i;a++)

How to get input box values and the select box values to store it in array and do calculation

I'm trying to get input box values and select box values to store it each one in array and do some calculation and I couldn't get a result here is my javascript code:-
$(window).on('pageinit', function() {
$(document).ready(function(){
$("#Scal").click(function() {
var x = parseFloat($('[name^="Sc"]').val()) || 0
var y = parseFloat($('[name^="Sgrade"]').val()) || 0
var sum1 = 0;
var sum2 = 0;
for(var i=0; i< x.length; i++) {
sum1 += x[i]*y[i];
sum2 += x[i];
}
var sum3 = sum1/sum2
var sum3 = sum3.toFixed(2)
$('#Sres').val(sum3)
});
});
});
You need to loop over the elements from which you're pulling the values. Your parseFloat approach isn't going to work.
Do something like this to get the sum of all Sc values:
$(document).ready(function () {
var sumSc = 0;
$("#Scal").click(function () {
//loop over the matching elements with jQuery each()
$('[name^="Sc"]').each(function () {
sumSc += +$(this).val(); //the extra "+" here coerces a Number value
});
console.log(sumSc); //this outputs your total in the console
});
});
You can apply that same approach to sum the other elements and do your calculations.

How to add a tick mark based on a counter in Javascript

I'm making a simple game in HTML/Javascript where everytime a button or hyperlink gets pressed it adds 1 to a counter
<script type="text/javascript">
var count = 0;
function countClicks() {
count = count + 1;
document.getElementById("p2").innerHTML = count;
}
</script>
My question is is there a way to also add a tick (Ascii #10004) equal to the number in the counter. I'm sure this is an easy solve but I've never really used Javascript and this seems the easiest language to do this all in. I appreciate any help given
You can use the HTML decimal: ☑
Just replace the code:
document.getElementById("p2").innerHTML = count;
with the following code:
document.getElementById("p2").innerHTML = "&#9745 "+count;
Or you can use:
document.getElementById("p2").innerHTML = "&#10004 "+count;
The result will be like this:
✔ 5
here 5 is your count.
Yes you can. You even don't need a loop to concatenate ticks.
see jsfiddle demo
var count = 5; // count is already 5 for demo purpose
function countClicks() {
count = count + 1;
var ticks = Array(count+1).join("✔");
document.getElementById("p2").innerHTML = count+' '+ticks;
}
countClicks(); # 6 ✔✔✔✔✔✔
Yes, you can use the String.fromCharCode to convert ascii code to character.
Example to display continuos ticks equal to number of count:
<script type="text/javascript">
var count = 0;
function countClicks() {
count = count + 1;
var res = String.fromCharCode(10004);
var output = "";
for (var i = 0; i < count; i++) {
output += res+" ";
}
document.getElementById("p2").innerHTML = output;
}
</script>
This will do :
http://jsfiddle.net/oL83m567/1/
var count = 0;
function countClicks() {
count = count + 1;
var tick='';
for(var i=0;i<count;i++)
tick+= '&#x2714';
document.getElementById("p2").innerHTML = count + tick;
}
It sounds like you want to ADD another tick every time the thing is pressed? I would do it like this:
var count = 0;
function countClicks() {
count = count + 1;
document.getElementById("p2").innerHTML = document.getElementById("p2").innerHTML + '&#10004';
}
Or, slightly more efficiently:
var p2, count = 0;
function countClicks() {
count = count + 1;
p2 = document.getElementById("p2");
p2.innerHTML = p2.innerHTML + '&#10004';
}
In that case, count becomes unnecessary, unless you need it for something else.
I'd go for doing it with an array. Advantage of this is that you have the ticks stored as elements in the array and can manipulate them later e.g. change a chosen tick to a cross or have a button which removes a tick. Something like:
<script type="text/javascript">
var ticks=new Array();
function countClicks() {
ticks[ticks.length]="✔";
document.getElementById("p2").innerHTML = ticks.join("");
}
</script>

I want to add all the values in the field Sum to the field Total but it is not working

Here, sums[i].value is getting right values but when I want to keep a grand total of all Sum, it is failing.
function calc() {
var amounts = document.getElementsByName("Amount");
var prices = document.getElementsByName("Price");
var sums = document.getElementsByName('Sum');
var tax = document.getElementsByName('Tax');
var total = document.getElementsByName('Total');
for (var i = 0; i < amounts.length; i++) {
sums[i].value = amounts[i].value * prices[i].value;
total[0].value = total[0].value + sums[i].value;
// only this line is not working
}
}
Plain HTML is strings, all the way down, and var amounts = document.getElementsByName("Amount"); followed by amounts.value means you now have string values. Since + is also a string operator, JavaScript will happily turn "2"+"4" into "24", which looks like it did maths, but wrong, when in fact it didn't do math at all.
Convert all values that need to be numbers into numbers, first:
var amounts = document.getElementsByName("Amount");
....
var amount = parseFloat(amounts.value); // NOW it's a number
...
Replace your code with :
for (var i = 0; i < amounts.length; i++) {
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
// only this line is not working
}
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
This should help you.
Remove the .value while adding and multiplying
function test()
{
var amounts = new Array();
amounts[0] = "4";
amounts[1] = "6";
amounts[2] = "10";
var prices = new Array();
prices[0] = "4";
prices[1] = "6";
prices[2] = "10";
var sums = new Array();
var total = 0;
for (var i = 0; i < amounts.length; i++) {
sums[i] = parseInt(amounts[i]) * parseInt(prices[i]);
total= parseInt(total) + parseInt(sums[i]);
// only this line is not working
//alert(total); is 152
}
}

Categories

Resources