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>
Related
I am struggling already for some time to create script that deletes and adds values to field. The point is that when I click on div - there will be images inside, it will copy part of its class to field, or remove if it's already copied there. All the values in field input_8_3 need to be comma separated without spaces except the last one and in case there is only one value there shouldn't be any comma. The same with field input_8_4, but there I need only erased values.
In addition I need divs to change class on click, one click to add class, another to remove it, but this is how far could I get with my issue.
I need this for deleting images in custom field in Wordpresses frontend. input_8_3 goes to meta and input_8_4 to array in function to delete chosen images.
Thanks in advance!
(function($){
$('.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','')+',';
var oldtext = $('#input_8_3').val();
$('#input_8_3').val(text+oldtext);
});
})(jQuery);
(function($){
$('div.thumbn').click(function() {
$(this).removeClass('chosen-img');
});
})(jQuery);
(function($){
$('.thumbn').click(function() {
$(this).addClass('chosen-img');
});
})(jQuery);
.thumbn {
width: 85px;
height: 85px;
background: #7ef369;
float: left;
margin: 10px;
}
.chosen-img.thumbn{background:#727272}
input{width:100%}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="input_8_3" readonly="" value="3014,3015,3016,3017,3018" class="form-control data_lable">
<input type="text" id="input_8_4" readonly="" value="" class="form-control data_lable">
<div class="user-profile-avatar user_seting st_edit">
<div>
<div class="thumbn" id="img-act-3014"></div>
<div class="thumbn" id="img-act-3015"></div>
<div class="thumbn" id="img-act-3016"></div>
<div class="thumbn" id="img-act-3017"></div>
<div class="thumbn" id="img-act-3018"></div>
</div>
</div>
EDIT: I changed value of input_8_3. All the numbers in img-act-**** and values in input_8_3 are the same on load.
I've made a JS of it working.
https://jsfiddle.net/jatwm8sL/6/
I've added these:
var array = [3008,3009,3010,3011,3012];
$("#input_8_3").val(array.join());
and changed your click functions to this
var array = [3008,3009,3010,3011,3012];
var array1 = [];
$("#input_8_3").val(array.join());
(function($){
$('div.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','');
var oldtext = $('#input_8_3').val();
if ($(this).hasClass('chosen-img'))
{
$('#input_8_3').val(text+oldtext);
var index = array.indexOf(text);
if (index !== -1)
{
array.splice(index, 1);
}
array1.push(text);
$(this).removeClass('chosen-img');
}
else
{
array.push(text);
var index = array1.indexOf(text);
if (index !== -1)
{
array1.splice(index, 1);
}
$(this).addClass('chosen-img');
}
$("#input_8_3").val(array.join());
$("#input_8_4").val(array1.join());
console.log(array1);
});
})(jQuery);
Basically, you need to check if it has a class and then remove if it has and add it if it doesn't.
Also, it's better to use a javascript array than to play around with html values as you change javascript arrays while HTML should really just display them.
If anything is unclear, let me know and I'll try to explain myself better
var transformNumbers = (function () {
var numerals = {
persian: ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"],
arabic: ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"]
};
function fromEnglish(str, lang) {
var i, len = str.length, result = "";
for (i = 0; i < len; i++)
result += numerals[lang][str[i]];
return result;
}
return {
toNormal: function (str) {
var num, i, len = str.length, result = "";
for (i = 0; i < len; i++) {
num = numerals["persian"].indexOf(str[i]);
num = num != -1 ? num : numerals["arabic"].indexOf(str[i]);
if (num == -1) num = str[i];
result += num;
}
return result;
},
toPersian: function (str, lang) {
return fromEnglish(str, "persian");
},
toArabic: function (str) {
return fromEnglish(str, "arabic");
}
}
})();
document.getElementById('ApproximateValue').addEventListener('input', event =>
event.target.value = TolocalInt(event.target.value)
);
function TolocalInt(value)
{
if ((value.replace(/,/g, '')).length >= 9) {
value = value.replace(/,/g, '').substring(0, 9);
}
var hasZero = false;
var value = transformNumbers.toNormal(value);
var result = (parseInt(value.replace(/[^\d]+/gi, '')) || 0);
if (hasZero) {
result = '0' + (result.toString());
}
return result.toLocaleString('en-US');
}
<input id="ApproximateValue" name="ApproximateValue" type="text" maxlength="12" />
I would like to balance two input number fields using jquery based on the max value set for both. for example its like a balance, if one side goes down the other goes up and vice versa. another example if the max value is 20 then if i enter 5 in input field one then 15 would be left in input field two.
Need the help Thanks. Haven't started coding it as yet stuck trying to figure it out.
First you need to attach the input eventhandler on all of the relevant input fields. This event handler will compare the current input value of a input fields to the total/max value variable and find the remainder accordingly. The event handler then finds the other input fields and assigns them with the appropriate remainder values.
Note: This allows you to add as many inputs as you want and it will
balance them all out. Just remember to add the balance class on the
input field.
var total = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
this.value = value = 0;
} else if (value > total) {
this.value = value = total;
}/* else if (value < 0) {
this.value = value = 0;
}
* Remove this comment if value shouldn't be negative.
*/
var remainder = total - value;
var otherInputs = $('.balance');
otherInputs.splice($.inArray(this,otherInputs),1);
var remainderDiv = remainder/otherInputs.length;
$.each(otherInputs, function(input) {
otherInputs[input].value = remainderDiv;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
Update: The two inputs can be less than the max but never higher.
var max = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
value = 0;
}
var otherInputs = $('.balance');
var sum = 0;
$.each(otherInputs, function(input) {
sum += parseInt(otherInputs[input].value);
});
if (sum > max)
this.value = max - (sum - value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
here's a fiddle to get you started (and maybe finished):
https://jsfiddle.net/ahmadabdul3/xwyrrw53/1/
html:
<input type='number' id='first' class='balancable'/>
<input type='number' id='second' class='balancable'/>
js:
$(function() {
var max = 20;
var balanceOpposite = {
'first': 'second',
'second': 'first',
}
$('.balancable').on('input', function() {
var id = $(this).attr('id');
var thisVal = $(this).val();
$('#' + balanceOpposite[id]).val(20 - thisVal);
});
});
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/
$(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;
}
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);
}