Format numbers with jquery numberformatter and format them back - javascript

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

Related

Multiplication in input with comma and special character

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>

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/

how to get dynamic id of dynamically created textbox in jquery

i want to perform keyup event via textbox id, and all textbox are dynamically created with onclick button event. for this i have to make 20 keyup function. if i use 20 keyup function then my code will become too lengthy and complex. instead of this i want to use a common function for all textbox. can anybody suggest me how to do it..thanks
here is what i am doing to solve it:
<div class="input_fields_wrap">
<button class="add_field_button">Add Booking</button></div>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
var counter = 2;
$(".add_field_button").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<div id="target"><label>Textbox #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="firsttextbox' + counter + '" value="" > <input type="text" name="textbox' + counter +
'" id="secondtextbox' + counter + '" value="" > Remove<input type="text" id="box' + counter + '" value="">sum</div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
function check(a, b) {
var first = a;
var second = b;
var temp = temp;
var novalue = "";
result = parseInt(first) + parseInt(second);
if (!isNaN(result)) {
return result;
} else {
return novalue;
}
}
$(this).on("keyup", "#firsttextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
var number = 2;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#firsttextbox3", function(e) {
var number = 3;
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#firsttextbox4", function(e) {
var number = 4;
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
final = document.getElementById('box4').value = result;
});
$(this).on("keyup", "#secondtextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#secondtextbox3", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#secondtextbox4", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
document.getElementById('box4').value = result;
});
$(this).on("click", "#remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('#target').remove();
counter--;
});
});
</script>
See the snippet below to see how you can make this implementation more modular and useable. The trick is to think: what do I want to do? I want to be able to add multiple inputs and add their value, printing the result in another input.
It comes down to using classes - since we are going to use the same kind of thing for every row. Then apply something that works for all classes. No IDs whatsoever! You can even use the name property of the input that contains the value you want to save. Using the [] in that property will even pass you back a nice array when POSTING!
I know this looks like a daunting lot, but remove my comments and the number of lines reduces dramatically and this kind of code is almost infinitely extendable and reusable.
But have a look, this works and its simple and - most of all - it's DRY (don't repeat yourself 0 once you do, re-evaluate as there should be a better way!)!
Update
You could also use a <ol>as a wrapper and then add an <li> to this every time, so you get automatic counting of boxes in the front end without any effort from your end! Actually, thats so nice for this that I have changed my implementation.
var add = $('#add_boxes');
var all = $('#boxes');
var amountOfInputs = 2;
var maximumBoxes = 10;
add.click(function(event){
// create a limit
if($(".box").length >= maximumBoxes){
alert("You cannot have more than 10 boxes!");
return;
}
var listItem = $('<li class="box"></li>');
// we will add 2 boxes here, but we can modify this in the amountOfBoxes value
for(var i = 0; i < amountOfInputs; i++){
listItem.append('<input type="text" class="input" />');
}
listItem.append('<input type="text" class="output" name="value" />');
// Lets add a link to remove this group as well, with a removeGroup class
listItem.append('<input type="button" value="Remove" class="removeGroup" />')
listItem.appendTo(all);
});
// This will tie in ANY input you add to the page. I have added them with the class `input`, but you can use any class you want, as long as you target it correctly.
$(document).on("keyup", "input.input", function(event){
// Get the group
var group = $(this).parent();
// Get the children (all that arent the .output input)
var children = group.children("input:not(.output)");
// Get the input where you want to print the output
var output = group.children(".output");
// Set a value
var value = 0;
// Here we will run through every input and add its value
children.each(function(){
// Add the value of every box. If parseInt fails, add 0.
value += parseInt(this.value) || 0;
});
// Print the output value
output.val(value);
});
// Lets implement your remove field option by removing the groups parent div on click
$(document).on("click", ".removeGroup", function(event){
event.preventDefault();
$(this).parent(".box").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<ol id="boxes">
</ol>
<input type="button" value="Add a row" id="add_boxes" />
You can target all your textboxes, present or future, whatever their number, with a simple function like this :
$(document).on("keyup", "input[type=text]", function(){
var $textbox = $(this);
console.log($textbox.val());
})
$("button").click(function(){
$("#container").append('<input type="text" /><br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="text" /><br>
<input type="text" /><br>
<input type="text" /><br>
</div>
<button>Create one more</button>
You don't need complicated generated IDs, not necessarily a class (except if you have other input[type=text] you don't want to conflict with). And you don't need to duplicate your code and write 20 times the same function. Ever. If you're duplicating code, you're doing wrong.
Add classes "a" and "b" to the textboxes and "box" to the box. Then add data-idx attribute with the index (unused!?). Finally register the event handlers:
$('.a').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= this.value;
var b= $p.find('.b').val()
var number =$this.data('idx') //unused!?
var result = check(a,b)
$p.find('.box').val(result)
})
$('.b').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= $p.find('.a').val()
var b= this.value
var result = check(a,b)
$p.find('.box').val(result)
})
Or a general one:
$('.a,.b').on('keyup', function(e){
e.preventDefault();
var $p = $(this).parent()
var a= $p.find('.a').val()
var b= $p.find('.b').val()
var result = check(a,b)
$p.find('.box').val(result)
})
You can assign a class to all textboxes on which you want to perform keyup event and than using this class you can attach the event on elements which have that class. Here is an example
var html="";
for (var i = 0; i < 20; i++)
{
html += "<input type='text' id='txt" + i + "' class='someClass' />";
}
$("#testDiv").html(html);
Attach keyup event on elements which have class someClass.
$(".someClass").keyup(function () {
alert($(this).attr("id"));
});
A little helper to combine with your favorite answer:
var uid = function () {
var id = 0;
return function () {
return ++id;
};
}();
Usage:
uid(); // 1
uid(); // 2
uid(); // 3
Providing a code-snippet which may give you some hint:
$(".add_field_button").click(function ()
{
if (counter > 10)
{
alert("Only 10 textboxes allow");
return false;
}
var txtBoxDiv = $("<div id='TextBoxDiv"+counter+"' style='float:left;width:10%; position:relative; margin-left:5px;' align='center'></div>");
//creating the risk weight
var txtBox1 = $('<input />',
{
'id' : 'fst_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox2 = $('<input />',
{
'id' : 'sec_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox3 = $('<input />',
{
'id' : 'sum_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
});
$(txtBoxDiv).append(txtBox1).append(txtBox2);
$(txtBoxDiv).append(txtBox3);
});
function txtBoxFun(obj, count)
{
var idGet = $(obj).attr('id');
var idArr = new Array();
idArr = idGet.split("_");
if(idArr[0] == "fst")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#sec_textbox_"+count).val()));
}
else if(idArr[0] == "sec")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#fst_textbox_"+count).val()));
}
$("#sum_textbox_"+count).val(sumTxt);
}

Word count jquery and stop user from typing

$(document).ready(function(){
$("input").keyup(function(){
if($(this).val().split(' ').length == 10){
alert();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Enter your name: <input type="text">
If the input is 1 2 3 4 5 6 7 8 9 the alert fired, I know it included the space. But how to stop user from adding more character (even space) when the limit is reached?
The problem can easily be simplified to disabling the spacebar when the max word count is reached:
this should work: http://jsfiddle.net/wznervgz/6/
<input data-max-words="10" />
js:
$('input[data-max-words]').on('keydown', function (e) {
var $txt = $(this),
max = $txt.data('maxWords'),
val = $txt.val(),
words = val.split(' ').length;
if (words === max && e.keyCode === 32)
return false;
});
Hope this will help you.
<textarea name="txtMsg" id="word_count" cols="1" rows="1"> </textarea>
<span style="padding-left:10px;">Total word Count :
<span id="display_count" style="font-size:16px; color:black;">0</span> words &
<span id="count_left" style="font-size:16px; color:black;">2</span> words left.</span>
<br>
jquery code:
var max_count = 2;
$(document).ready(function () {
var wordCounts = {};
$("#word_count").keyup(function () {
var matches = this.value.match(/\b/g);
wordCounts[this.id] = matches ? matches.length / 2 : 0;
var finalCount = 0;
$.each(wordCounts, function (k, v) {
finalCount += v;
});
var vl = this.value;
if (finalCount > max_count) {
vl = vl.substring(0, vl.length - 1);
this.value = vl;
}
var countleft = parseInt(max_count - finalCount);
$('#display_count').html(finalCount);
$('#count_left').html(countleft);
am_cal(finalCount);
});
}).keyup();
Fiddle link: http://jsfiddle.net/aVd4H/32/
Thank you.
Think about storing the value of the input after each keyup and if the wordcount is greater than your limit just setVal back to the "previously" saved amount. So it would start off as var previousVal = ''; and then increment accordingly until the comparison returns true, set the val and return.
Demo: http://jsfiddle.net/robschmuecker/wznervgz/1/
$(document).ready(function(){
var previousValue = '';
$("input").keydown(function(){
if($(this).val().split(' ').length >= 10){
alert();
$(this).val(previousVal);
return;
}
previousVal = $(this).val();
});
});
You can try this:
$("input").keydown(function(e){
if($(this).val().split(' ').length == 10){
alert();
e.preventDefault();
return false;
}

If input field is empty fill it with random number

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.

Categories