The goal is: If I write in first input 10,000 (which should be 10000) and multiply it by 0.005 then must be 50, but now is 0,50 - Just remove "," when using multiplication.
Also I want to add "$" symbol when function showing me final value. ($10000)
<input type="text" id="results-input-1"></p>
<input type="text" id="results-input-2" value="0.005"/>
<span id="results-cal-final">$</span>
<script>
var multiplyShares = function() {
var val1 = parseFloat($('#results-input-1').val())
var val2 = parseFloat($('#results-input-2').val())
val3 = val1 * val2 || "Invalid"
$("#results-cal-final").html(val3)
}
$("#results-input-1").keyup(function() { multiplyShares(); });
$("#results-input-2").keyup(function() { multiplyShares(); });
</script>
You can remove the , using $('#results-input-1').val().replace(/,/g, "").
The proper location to add $ is at .html(). You can also call .toFixed(2) to add decimal places in the displayed value.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Type 10,000 below:<br>
<input type="text" id="results-input-1"></p>
<input type="text" id="results-input-2" value="0.005"/>
<span id="results-cal-final">$</span>
<script>
var multiplyShares = function() {
var val1 = parseFloat($('#results-input-1').val().replace(/,/g, ""))
var val2 = parseFloat($('#results-input-2').val())
var val3 = val1 * val2;
if (val3) {
// add two decimals if needed, prepend $
val3 = "$" + /^\d+(\.\d{1,2})?$/.test(val3+'') ? val3.toFixed(2) : val3);
} else {
val3 = "Invalid";
}
$("#results-cal-final").html(val3)
}
$("#results-input-1").keyup(function() { multiplyShares(); });
$("#results-input-2").keyup(function() { multiplyShares(); });
</script>
You can do something as below for a crude idea of the solution.
Replace all the , by the empty space and multiply normally as you are doing.
<input type="text" id="results-input-1"></p>
<input type="text" id="results-input-2" value="0.005"/>
<span id="results-cal-final"></span>
<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E="
crossorigin="anonymous"></script>
<script>
var multiplyShares = function() {
var val1 = parseFloat($('#results-input-1').val().replace(',',''))
var val2 = parseFloat($('#results-input-2').val())
val3 = val1 * val2 || "Invalid"
$("#results-cal-final").html(val3 !== 'Invlid' ? ('$' + val3) : 'Invlid')
}
$("#results-input-1").keyup(function() { multiplyShares(); });
$("#results-input-2").keyup(function() { multiplyShares(); });
</script>
Related
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>
I'm trying to write a function that when a user clicks "plus" or "minus" an input box is updated with an integer only I need to add the commas on each click manually.
If you click minus, it works at first but hitting it again renders it NaN. If I console.log this value it strips all characters after the first comma, this may not make much sense but take a look at the fiddle for a better example...
JS
function addCommas(intNum) {
return (intNum + '').replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
$('#plus').on('click', function() {
var value = $("#propertyValueSliderValue").val();
$("#propertyValueSliderValue").val(addCommas(value));
});
$('#minus').on('click', function() {
var curVal = $("#propertyValueSliderValue").val();
var val = 500;
var newVal = curVal - val;
//newVal = newVal.replace(/,/g, "");
alert( newVal );
$("#propertyValueSliderValue").val(addCommas(newVal));
});
https://jsfiddle.net/5qhof0fq/1/
instead of var curVal = $("#propertyValueSliderValue").val(); in minus function,
remove the commas and then parse it.
var curVal = $("#propertyValueSliderValue").val();
curVal = parseInt(curVal.replace(/,/g, ""))
The issue is because the , is meaning that the value from the input cannot be coerced to an integer. You need to replace the commas before performing any mathematical operations: .replace(/,/g, '')
function addCommas(intNum) {
return (intNum + '').replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
$('#plus').on('click', function() {
var value = $("#propertyValueSliderValue").val().replace(/,/g, '');
$("#propertyValueSliderValue").val(addCommas(value));
});
$('#minus').on('click', function() {
var curVal = $("#propertyValueSliderValue").val().replace(/,/g, '');
var val = 500;
var newVal = curVal - val;
$("#propertyValueSliderValue").val(addCommas(newVal));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-slider property-value">
<div class="slider-wrap">
<div id='minus'>-</div>
<div id='plus'>+</div>
</div>
<div class="slider-value money">
<input class="s-value number" type="tel" id="propertyValueSliderValue" value="120000" />
</div>
</div>
Alternatively, you can use a data attribute to hold the value to use in the calculation while keeping the UI-friendly value separate. You can also use another data attribute to hold the increment to be added/removed from the value so that you can DRY up the click event handlers:
function addCommas(intNum) {
return (intNum + '').replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
var $propertySliderValue = $("#propertyValueSliderValue");
$('.inc').on('click', function() {
var value = $propertySliderValue.data('value') + $(this).data('inc');
$propertySliderValue.val(addCommas(value)).data('value', value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-slider property-value">
<div class="slider-wrap">
<div id='minus' class="inc" data-inc="-500">-</div>
<div id='plus' class="inc" data-inc="500">+</div>
</div>
<div class="slider-value money">
<input class="s-value number" type="tel" id="propertyValueSliderValue" data-value="120000" value="120,000" />
</div>
</div>
It happens because when you get the value out the #propertyValueSliderValue it is a String:
change your code to this:
$('#minus').on('click', function() {
var curVal = $("#propertyValueSliderValue").val();
var parseVal = parseInt(curVal);
var val = 500;
var newVal = parseVal - val;
//newVal = newVal.replace(/,/g, "");
alert( newVal );
$("#propertyValueSliderValue").val(addCommas(newVal));
});
It's because you read the value out of the input every time, and technically a number with the comma isn't a number in javascript.
What you can do is make a variable to keep track of the real number and only output the comma version to the user.
var value = parseInt($("#propertyValueSliderValue").val());
var interval = 500;
function addCommas(intNum) {
return (intNum + '').replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
$('#plus').on('click', function() {
value += interval;
var commaNotatedVal = addCommas(value);
$("#propertyValueSliderValue").val(commaNotatedVal);
});
$('#minus').on('click', function() {
value -= interval;
var commaNotatedVal = addCommas(value);
$("#propertyValueSliderValue").val(commaNotatedVal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-slider property-value">
<div class="slider-wrap">
<div id='minus'>-</div>
<div id='plus'>+</div>
</div>
<div class="slider-value money">
<input class="s-value number" type="tel" id="propertyValueSliderValue" value="120000" />
</div>
</div>
I have a problem.
$('#value-salary').on('keyup', function(){
if($(this).val() != ""){
var n = parseInt($(this).val().replace(/\D/g,''),10);
$(this).val(n.toLocaleString());
}
});
This allow me to see "." as thousand separator while typing. Before submit I will replace "." with "" and for now it's all ok.
The problem is that the keyup doesn't allow me to insert "," and I need to use this as decimal separator (before sending i will replace , with . but user is not interested in rest api. He want to see "," as decimal separator).
How can i fix this problem? Keypress or keydown are not good solutions...thanks!
you can use autoNumeric.js.
$(".testInput").autoNumeric('init', {
aSep: '.',
aDec: ',',
aForm: true,
vMax: '999999999',
vMin: '-999999999'
});
<input class="testInput" type="text" value="8000"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/autonumeric/1.8.2/autoNumeric.js"></script>
please see more information how to use numeric.
http://www.decorplanit.com/plugin/
You can try this piece of code. It places , as thousand separator and you can use . for your decimal separator. You can easily customize the symbols you want to use for each purpose.
<html>
<head>
<script language="javascript" type="text/javascript">
function thousandSeparator(n, sep) {
var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
sValue = n + '';
if (sep == undefined) { sep = ','; }
while (sRegExp.test(sValue)) {
sValue = sValue.replace(sRegExp, '$1' + sep + '$2');
}
return sValue;
}
function showSeparator() {
var myValue = document.getElementById("txtInvoicePrice").value;
myValue = thousandSeparator(myValue.replace(/,/g, ""), ',');
document.getElementById("txtInvoicePrice").value = myValue;
}
function removeSeparator() {
var myValue = document.getElementById("txtInvoicePrice").value;
myValue = myValue.replace(',', '');
document.getElementById("txtInvoicePrice").value = myValue;
}
</script>
</head>
<body>
<input type="text" id="txtInvoicePrice" onfocus="javascript:removeSeparator();" onblur="javascript:showSeparator();" />
</body>
</html>
It works for me with javascript code:
<input type="text" name="xxx" onkeyup="ididit(this,this.value.charAt(this.value.length-1))" value=""/>
And:
<script>
function ididit(donde,caracter) {
pat = /[\*,\+,\(,\),\?,\\,\$,\[,\],\^]/
valor = donde.value
largo = valor.length
crtr = true
if(isNaN(caracter) || pat.test(caracter) == true) {
if (pat.test(caracter)==true) {
caracter = "\\" + caracter
}
carcter = new RegExp(caracter,"g")
valor = valor.replace(carcter,"")
donde.value = valor
crtr = false
} else {
var nums = new Array()
cont = 0
for(m=0;m<largo;m++) {
if(valor.charAt(m) == "," || valor.charAt(m) == " ") {
continue;
}else{
nums[cont] = valor.charAt(m)
cont++
}
}
}
var cad1="",cad2="",tres=0
var cad3="",cad4=""
if(largo > 3 && crtr == true) {
if (nums[0]=="$"){
nums.shift()
}
for (k=nums.length-1;k>=0;k--) {
cad1 = nums[k]
cad2 = cad1 + cad2
tres++
if((tres%3) == 0) {
if(k!=0){
cad2 = "," + cad2
}
}
if (k==0) {
cad2 = "$ " + cad2
}
}
donde.value = cad2
} else if (largo <= 3 && crtr == true) {
if (nums[0]=="$"){
nums.shift()
}
for (k=nums.length-1;k>=0;k--) {
cad3 = nums[k]
cad4 = cad3 + cad4
if (k==0) {
cad4 = "$ " + cad4
}
}
donde.value = cad4
}
}
</script>
I format numbers of an input field with jquery numberformatter, that works, but I have to format them back in order to do some calculations on the numbers, but that doesn't work. How can I convert the formatted numbers back so that I can use the calculate function?
Here is the JS for the number formatting:
$("[id$='abzug']").keyup(function(){
$(this).parseNumber({format:"#,###", locale:"ch"});
$(this).formatNumber({format:"#,###", locale:"ch"});
val();
});
Here the HTML:
<input class="form-control" id="kunst_abzug" type="text">
<input class="form-control" id="theater_abzug" type="text">
And here the function to calculate the total:
function id(id){return document.getElementById(id);}
function val(){
val_totalEingespart = parseInt(id("totalEingespart").value) || 0;
val1 = parseInt(id("kunst_abzug").value) || 0;
val2 = parseInt(id("theater_abzug").value) || 0;
var total_abgezogen = val_totalEingespart - val1 - val2;
var total_abgezogenCHF = total_abgezogen.toLocaleString('de-CH');
id("totalSum2").innerHTML = total_abgezogenCHF + ' CHF';
}
I also created a js fiddle: http://jsfiddle.net/Lffpg4xp/2/
Remove the onkeyup="val() from each input element and add it to the keyup of function in document.ready.
$( document ).ready(function() {
$("[id$='abzug']").keyup(function(){
$(this).parseNumber({format:"#,###", locale:"ch"});
$(this).formatNumber({format:"#,###", locale:"ch"});
val();
});
});
function getElementValue(id){
var num = $('#' + id).val();
return $.parseNumber(num, {format:"####", locale:"ch"});
}
function val(){
val_totalEingespart = parseInt(getElementValue("totalEingespart")) ? parseInt(getElementValue("totalEingespart")) : 0;
val1 = parseInt(getElementValue("kunst_abzug")) ? parseInt(getElementValue("kunst_abzug")) : 0;
val2 = parseInt(getElementValue("theater_abzug")) ? parseInt(getElementValue("theater_abzug")) : 0;
var total_abgezogen = val_totalEingespart - val1 - val2;
$("#totalSum2")[0].innerHTML = total_abgezogen.toLocaleString('de-CH') + ' CHF';
}
Updated fiddle
I want to fill all empty number fields with a random number. I can populate all fields with a random number as shown below.
$.each(numberField, function () {
x = Math.floor((Math.random() * 10) + 1);
($(this).val(x));
});
But if I try and wrap it around an
if (numberField.val() === "")
It doesn't work
What am I doing wrong here? see fiddle
<input type="number" value="0">
<input type="number" value="">
<input type="number" value="4">
<input type="number" value="5">
<input type="number" value="">
var numberField = $('input[type=number]');
var x = '';
if (numberField.val() === "") {
$.each(numberField, function () {
x = Math.floor((Math.random() * 10) + 1);
($(this).val(x));
});
}
You need to move your condition (you are looking if an array is equal to "", which is never the case). You also need to trim the value to check if it is really empty:
var numberField = $('input[type=number]');
var x = '';
$.each(numberField, function () {
if ($.trim($(this).val()) === "") {
x = Math.floor((Math.random() * 10) + 1);
($(this).val(x));
}
});
in your example numberField is an array so your code must be like this:
var numberField = $('input[type=number]');
var x = '';
$.each(numberField, function () {
if ($(this).val() === "") {
x = Math.floor((Math.random() * 10) + 1);
$(this).val(x);
}
});
See the updated fiddle.
$.each(numberField, function (k, v) {
if ($(v).val() === "") {
x = Math.floor((Math.random() * 10) + 1);
($(v).val(x));
}
});
Take a look at the doc for the jQuery each function.
try this...
var numberField = $('input[type=number]');
var x = '';
$.each(numberField, function () {
if (this.value === "") { // should check the value inside the loop.. not outside
x = Math.floor((Math.random() * 10) + 1);
this.value = x;
}
});
demo
I think the problem is here:
numberField.val()
instead, use
$(this).val()
so ...
var numberField = $('input[type=number]');
var x = '';
$.each(numberField, function () {
alert($(this).val());
if ($(this).val() === ""){
x = Math.floor((Math.random() * 10) + 1);
($(this).val(x));
};
});
updated Fiddle
http://jsfiddle.net/aaronk85/eC48k/
You can match only the fields with no value like this:
$('input[type=number][value=""]').each(function () {
this.value=Math.floor((Math.random() * 10) + 1);
});
Here's the demo.