Grand Total Calculation in Javascript to handle currency format (MinusSignNegative) - javascript

I currently have a javascript code below that calculates a grand total into a read only text field when dealing with currency formats i.e. $500.00. The problem that I am running into is how to handle the calculation when more than one negative number is entered in currency format (MinusSignNegative) i.e. ($500.00) instead of -$500.00. I am currently getting a NaN error in the grand total.
I believe that this regex should handle it but I can't figure out how to implement. http://www.regexlib.com/(X(1)A(bk8AHOFYowt7XHOC4WUCtfdM2LhlaovTNInhWLTrzAeoeq-c53XkkdwLD-WDe3OgQtJ7BLHSs0P-u-RrLbfVZaQIHkBH2exYGw0qtz6nqSamZNVqtnyufo9Y3nrEq5mq-mry63HY4Nnv0dfsQOZzKvuwcKAuwigyyQva-67laxr-ModxTQESW8fXx2XJL_0L0))/REDetails.aspx?regexp_id=625&AspxAutoDetectCookieSupport=1
Can anybody offer a solution?
<SCRIPT LANGUAGE="JavaScript">
<!--
function total(what,number) {
var grandTotal = 0;
for (var i=0;i<number;i++) {
if (what.elements['price' + i].value.replace(/\$|\,/g,'') == '')
what.elements['price' + i].value.replace(/\$|\,/g,'') == '0.00';
grandTotal += (what.elements['price' + i].value.replace(/\$|\,/g,'') - 0);
}
what.grandTotal.value = (Math.round(grandTotal*100)/100);
}
//-->
</SCRIPT>
<FORM NAME="myName">
Tax Due/Refund: <input TYPE="text" NAME="price0" VALUE="" SIZE="10" class='currency' onChange="total(this.form,3)"><BR>
Interest: <input TYPE="text" NAME="price1" VALUE="" SIZE="10" class='currency' onChange="total(this.form,3)"><BR>
Penalty: <input TYPE="text" NAME="price2" VALUE="" SIZE="10" class='currency' onChange="total(this.form,3)"><BR>
Total Amount Assessed: <INPUT TYPE="TEXT" NAME="grandTotal" class='currency' SIZE="25" READONLY="readyonly" style="background:#eee none; color:#222; font-weight:bold">
</FORM>

If you are trying to move a negative sign from the number to the left of a dollar sign,
do it when you write the total value field.
function total(what, number){
var grandTotal= 0, i= number, val, sign;
while(i){
val= what.elements['price' + i--].value.replace([$, ]+/g,'') ;
grandTotal+= parseFloat(val) || 0;
}
sign= grandTotal<0? '-' :'';
what.grandTotal.value= sign+'$'+ Math.abs(Math.round(grandTotal*100)/100);
}

You can do it with or without that regex.
Without:
fieldValue = field.value; // "(500.00)"
// search for a "(" char
if (fieldValue.indexOf("(") >= 0) {
// remove all chars, but numbers and dots
fieldValue = fieldValue.replace(/[^0-9.]/ig, "");
// 500.00
numberFieldValue = Number(fieldValue) * -1;
}
With:
fieldValue = field.value; // "(500.00)"
// test if the value matches that pattern for negative numbers
if (fieldValue.match(/PUT_THAT_REGEX_HERE/g)) {
// remove all chars, but numbers and dots
fieldValue = fieldValue.replace(/[^0-9.]/ig, "");
// 500.00
numberFieldValue = Number(fieldValue) * -1;
}
it should look like this:
function total(what,number) {
var grandTotal = 0;
for (var i=0;i<number;i++) {
fieldValue = what.elements['price' + i].value; // "(500.00)"
// search for a "(" char
if (fieldValue.indexOf("(") >= 0) {
// remove all chars, but numbers and dots
fieldValue = fieldValue.replace(/[^0-9.]/ig, "");
// 500.00
numberFieldValue = Number(fieldValue) * -1;
} else if (fieldValue.replace(/\$|\,/g,'') == '') {
numberFieldValue = 0;
} else {
numberFieldValue = number(fieldValue.replace(/\$|\,/g,''));
}
grandTotal += numberFieldValue ;
}
what.grandTotal.value = (Math.round(grandTotal*100)/100);
}

Related

Can't get this javascript (Luhn Algorithm) to work in this perl CGI file

I have a shopping cart that doesn't validate cards and I'm getting a lot of declined orders because people don't catch their typos. Trying to add Luhn validation to it.
I found this script which works fine by itself. It on-the-fly changes invalid to valid when a "good" credit card number is typed in.
<input id="cc" type="text" name="creditcard" size="20"><p id="status">invalid</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('#cc').on('input', function(){
if (checkLuhn($('#cc').val())) {
$('#status').html('valid');
} else {
$('#status').html('invalid');
}
});
function checkLuhn(value) {
// remove all non digit characters
var value = value.replace(/\D/g, '');
var sum = 0;
var shouldDouble = false;
// loop through values starting at the rightmost side
for (var i = value.length - 1; i >= 0; i--) {
var digit = parseInt(value.charAt(i));
if (shouldDouble) {
if ((digit *= 2) > 9) digit -= 9;
}
sum += digit;
shouldDouble = !shouldDouble;
}
return (sum % 10) == 0;
}
</script>
I'm trying to insert it into the HTML portion of the CGI file, below this relevant line and giving the INPUT the id="cc" tag, but the script won't run.
<INPUT TYPE="text" id="cc" NAME="Payment_Card_Number" MAXLENGTH="20" size="20" value="$form_data{'Payment_Card_Number'}">

Why is my character counter not excluding spaces?

I am making a character counter with HTML, CSS, JS. I got the counter working, but I have a checkbox that should get the length of the input without the spaces, but it is not working. Please check my code and tell me what's wrong.
function char_count(str, letter) {
var letter_Count = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == letter) {
letter_Count += 1;
}
}
return letter_Count;
}
function countChars(obj) {
var length = obj.value.length;
var output = document.getElementById("chars");
var dis = document.getElementById("removeSpace");
if (dis.checked) {
var spaces = char_count(obj, " ");
length = length - spaces;
output.innerHTML = length + ' characters';
} else {
output.innerHTML = length + ' characters';
}
}
<h1> Character Counter </h1>
<textarea id="input" onkeyup="countChars(this)" placeholder="Enter your text here..." autofocus></textarea>
<input type="checkbox" id="removeSpace">
<label for="removeSpace" onclick="countChars(document.getElementById('input'))">Don't Include Spaces</label>
<span id="chars">0 Characters</span>
You could make the code more simpler. Moreover, you have placed the checkbox outside the label that has onclick="countChars(document.getElementById('input'))", that's why the condition dis.checked in js does not find the checkbox as checked. Place the checkbox inside the label.
The whole simplified code would be like this,
<h1> Character Counter </h1>
<textarea id="input" onkeyup="countChars(this)" placeholder="Enter your text here..." autofocus></textarea>
<label for="removeSpace" onclick="countChars(document.getElementById('input'))">
<input type="checkbox" id="removeSpace">
Don't Include Spaces</label>
<span id="chars">0 Characters</span>
<script>
function countChars(obj) {
var length = obj.value.length;
var output = document.getElementById("chars");
var dis = document.getElementById("removeSpace");
if (dis.checked) {
length = obj.value.replace(/\s/g, '').length
}
output.innerHTML = length + ' characters';
}
</script>

how to replace input numbers with commas after key presses

I want to replace a number over 100 with commas. Like 1000 to 1,000 and 1000000 to 1,000,000 etc. in HTML. I have found the code on here to do so but it only works with predetermined numbers being passed. I don't want it to work for a predetermined number but for any number typed into the box.
<label for="turnover">Estimated Monthly Card Turnover:</label><br />
<span>£ </span><input type="text" id="turnover" maxlength="11"
name="turnover" size="10" required>*
<br /><br />
<script type="text/javascript">
$('#turnover').keydown(function(){
var str = $(this).val();
str = str.replace(/\D+/g, '');
$(this).val(str.replace(/\B(?=(\d{3})+(?!\d))/g, ","));});
</script>
I created a solution using pure javascript.
function onChange(el) {
var newValue = el.value.replace(/,/g, '');
var count = 0;
const last = newValue.substring(newValue.length - 1, newValue.length); // last input value
// check if last input value is real a number
if (!isNumber(last)) {
el.value = el.value.substring(0, el.value.length - 1);
return;
}
newValue = newValue.split('')
.reverse().map((it) => {
var n = it;
if (count > 0 && count % 3 == 0) n = n + ',';
count++;
return n;
})
.reverse().join('')
el.value = newValue
// document.getElementById('value').innerHTML = newValue
}
function isNumber(input) {
return input.match(/\D/g) == undefined;
}
<label>Number</label>
<input id="numbers" onkeyup="onChange(this)">
There are a couple of issues with your code:
It runs once when the page loads, not after that. I added a button to fix that.
The id used in your code does not match the actual id of the input field.
Input fields must be read and written using .val(). .text() works only for divs, spans etc.
Note that the conversion now works one time, after that it fails to properly parse the new text which now contains the comma(s).
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function ShowComma() {
console.clear();
var val = parseInt($("#comma").val());
console.log(val);
val = numberWithCommas(val);
console.log(val);
$("#comma").val(val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="turnover">Estimated Monthly Card Turnover:</label><br />
<span>£ </span><input type="value" id="comma" maxlength="30" name="turnover" size="10" required>*
<button onclick="ShowComma()">Show Comma</button>
To finalise this I have putgetElementById functions in so that this will work with a wordpress contact form 7. This must be with a text field though as it will not work with the number field as it will now accept commas:
<script>
document.getElementById("averagetrans").onkeyup = function() {onChange(this)};
document.getElementById("Turnover").onkeyup = function() {onChange(this)};
</script>
<script type="text/javascript">
function onChange(el) {
var newValue = el.value.replace(/,/g, '');
var count = 0;
const last = newValue.substring(newValue.length - 1, newValue.length); // last input value
// check if last input value is real a number
if (!isNumber(last)) {
el.value = el.value.substring(0, el.value.length - 1);
return;
}
newValue = newValue.split('')
.reverse().map((it) => {
var n = it;
if (count > 0 && count % 3 == 0) n = n + ','; // put commas into numbers 1000 and over
count++;
return n;
})
.reverse().join('')
el.value = newValue
// document.getElementById('value').innerHTML = newValue
}
function isNumber(input) {
return input.match(/\D/g) == undefined;
}
</script>

logical condition in jquery

My jquery function is like this i want to check when user enter netWeight greater than gross weight at that i want to give alert on it's blur. But it's not working i get both weight on alert but i have with this condition
function checkWeight(aboj)
{
var row = $(aboj).parents('.itemRow');
var gWeight = row.find('.gWeight').val() != '' ? row.find('.gWeight').val() : 0;
var netWeight = row.find('.netWeight').val() != '' ? row.find('.netWeight').val() : 0;
if(gWeight > netWeight)
{
alert("Please Check Gross Weight");
}
}
my html is like this
<input type="text" class="input netWeight" name="netWeight[]" onblur=" checkWeight(this);>
You're comparing strings. You need to parse the string value to float or integer to make the numeric comparison:
parseInt
parseFloat
$('body').on('click', '#compare', function () {
var gross = parseFloat($('#gross').val());
var net = parseFloat($('#net').val());
if (gross>net) {
alert('gross: ' + gross + ' is greater than net: ' + net);
}
if(net>gross) {
alert('net: ' + net + ' is greater than gross: ' + gross);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Gross:<input type="text" id="gross"/>
<br/>
Net:<input type="text" id="net"/>
<br/>
<input type="button" id="compare" value="Compare"/>
me get salutation with using parseFloat
function checkWeight(aboj)
{
var row = $(aboj).parents('.itemRow');
var gWeight = row.find('.gWeight').val() != '' ? row.find('.gWeight').val() : 0;
var netWeight = row.find('.netWeight').val() != '' ? row.find('.netWeight').val() : 0;
if(parseFloat(gWeight) < parseFloat(netWeight))
{
alert("Please Check Gross Weight");
}
}

Formatting number as thousand using only Javascript

Console.log is showing the correct result, but how can I add the same formatting to the input type while typing.
Input type is reset after every comma to zero.
1000 to 1,000
Please Help.
This code is working here
function numberWithCommas(number) {
if (isNaN(number)) {
return '';
}
var asString = '' + Math.abs(number),
numberOfUpToThreeCharSubstrings = Math.ceil(asString.length / 3),
startingLength = asString.length % 3,
substrings = [],
isNegative = (number < 0),
formattedNumber,
i;
if (startingLength > 0) {
substrings.push(asString.substring(0, startingLength));
}
for (i=startingLength; i < asString.length; i += 3) {
substrings.push(asString.substr(i, 3));
}
formattedNumber = substrings.join(',');
if (isNegative) {
formattedNumber = '-' + formattedNumber;
}
document.getElementById('test').value = formattedNumber;
}
<input type="number" id="test" class="test" onkeypress="numberWithCommas(this.value)">
Some notes:
Because you want commas, the type is not a number, it's a string
Because you want to work on the input after you type, it's onkeyup not onkeypressed
I have a solution that does a regex replace for 3 characters with 3 characters PLUS a comma:
var x = "1234567";
x.replace(/.../g, function(e) { return e + ","; } );
// Gives: 123,456,7
i.e. almost the right answer, but the commas aren't in the right spot. So let's fix it up with a String.prototype.reverse() function:
String.prototype.reverse = function() {
return this.split("").reverse().join("");
}
function reformatText() {
var x = document.getElementById('test').value;
x = x.replace(/,/g, ""); // Strip out all commas
x = x.reverse();
x = x.replace(/.../g, function(e) { return e + ","; } ); // Insert new commas
x = x.reverse();
x = x.replace(/^,/, ""); // Remove leading comma
document.getElementById('test').value = x;
}
<input id="test" class="test" onkeyup="reformatText()">
function numberWithCommas(x) {
var real_num = x.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
console.log(real_num);
document.getElementById('test').value = real_num;
}
<input type="number" id="test" onkeypress="numberWithCommas(this.value)">
Check out my fiddle here http://jsfiddle.net/6cqn3uLf/
You'd need another regex to limit to numbers but this will format based on the user's locale - which may be advantageous here.
<input id="mytext" type="text">
$(function () {
$('#btnformat').on('input propertychange paste', function () {
var x = $('#btnformat').val();
$('#btnformat').val(Number(x.replace(/,/g,'')).toLocaleString());
});
});
if jquery is not overhead for your application then you can use
https://code.google.com/p/jquery-numberformatter/

Categories