Limit character length and add hyphen in javascript - javascript

Hello I am trying to make a code is entered and a - is added before the last two digits and is six characters long without the hyphen , the codes that I attach work, but separately, it doesn't matter if I try to join them to make it work or call them independent the result is always the same:
the code length is limited to 5, and the hyphen ends in the last character
how can I solve that?
function check(code) {
var r = code.value.replace('.', '');
vlr = r.replace('-', '');
body = r.slice(0, -2);
dv = vlr.slice(-2).toUpperCase();
code.value = body + '-' + dv
if ( body.length < 4 ||body.length > 6) {
patente.setCustomValidity("incorrect");
return false;
}
code.setCustomValidity('');
}
$(document).ready(function () {
var code = 6;
$('#code').keydown( function(e){
if ($(this).val().length >= code) {
$(this).val($(this).val().substr(0, code));
}
});
$('#code').keyup( function(e){
if ($(this).val().length >= code) {
$(this).val($(this).val().substr(0, code));
}
});
});

Related

make sure first three digits of phone number are not 0's, using javascript

I am trying to validate a phone number with javascript and I'm stuck at this part
The area code (first 3 numbers in 999) can't be all zeros (0)'s
I know the code to make which ever format i want (say xxx-xxx-xxxx) but how do I make sure the first 0 arent all zeroes?
any help is appreciated, thank you!!
You can do this in many ways, here's a few examples using different methods.
Using startsWith
var num = "000-xxx-xxxx";
if (num.startsWith("000") === true) {
console.log("Number starts with 000");
}
Using substr
var num = "000-xxx-xxxx";
var first_three = num.substr(0, 3);
if (first_three === "000") {
console.log("Number starts with 000");
}
Using split
var num = "000-xxx-xxxx";
var first_three = num.split("-")[0];
if (first_three === "000") {
console.log("Number starts with 000");
}
Using a regular expression
var num = "000-xxx-xxxx";
if (/^000/.test(num)) {
console.log("Number starts with 000");
}
You can use parseInt, it will ignore everything after the first non-numeric character in the string:
var phone1 = '000-555-4444';
var phone2 = '555-555-5555';
function isValidAreaCode(phoneNumber) {
return parseInt(phoneNumber, 10) > 0;
}
console.log(phone1, 'valid?', isValidAreaCode(phone1));
console.log(phone2, 'valid?', isValidAreaCode(phone2));
You can use ^[0]{3}$ or ^\d{3}$
Assuming you are testing American area codes, using the regular expression
/^[2-9][0-8][0-9]/ to test them should work. According to
this.
Areacodes can start with a number between 2 and 9, the second number can be any
number except 9 and the last number can be any number.
function hasValidAreaCode(num) {
var stripped = num.replace(/\D/g, ''); // remove any no-numeric characters
return /^[2-9][0-8][0-9]/.test(stripped);
}
Interactive example:
function hasValidAreaCode(num) {
var stripped = num.replace(/\D/g, ''); // remove any no-numeric characters
return /^[2-9][0-8][0-9]/.test(stripped);
}
var elPhonenumber = document.getElementById('phonenumber');
elPhonenumber.addEventListener('keyup', function (event) {
var v = elPhonenumber.value;
if (v.replace(/\D/g, '').length > 2) {
var valid = hasValidAreaCode(v);
if (valid) {
elPhonenumber.classList.add('valid');
elPhonenumber.classList.remove('invalid');
} else {
elPhonenumber.classList.remove('valid');
elPhonenumber.classList.add('invalid');
}
} else {
elPhonenumber.classList.remove('valid', 'invalid');
}
});
.valid, .invalid {
color: #000;
}
.valid {
color: green;
}
.invalid {
color: red;
}
<label for="phonenumber">Please enter a phonenumber</label> <input id="phonenumber">

Insert a Comma in the thousandths place in outputted number [duplicate]

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 6 years ago.
I have created a function that takes a number in Imperial units entered into a div and converts that value to metric units in another div. Being relatively new to js, I am now realizing that a thousandths place comma separator does not come standard. I've tried to apply many of the solutions (many of them reg ex's) that I've found but none suit my needs or have worked. Simply put, I am just looking to have both divs outputted numbers have commas separating the thousandths place. Ultimately, these numbers are elevation values expressed in Feet and Meters. Any insight would be greatly appreciated... thanks!
Here is my code:
<body>
<div id="feet" onload="calculateMeter()">2120</div>
<div id="meter"></div>
<script>
var feet = document.getElementById('feet');
var meter = document.getElementById('meter');
function calculateMeter() {
if (feet.innerHTML > 0) {
meter.innerHTML = (feet.innerHTML * 0.3048).toFixed(1);
feet.toString();
feet = feet.innerHTML.replace(/(\d)(\d{3})\,/, "$1,$2.");
}
}
calculateMeter();
</script>
</body>
Here is a simple RegEx solution
function calculateMeter() {
if (feet.innerHTML > 0) {
var m = (feet.innerHTML * 0.3048).toFixed(2);
meter.innerHTML = m.replace(/\B(?=(\d\d\d)+\b)/g, ",");
}
}
It seems your problem is actually just setting the content the DOM element. Using the solution in How to print a number with commas as thousands separators in JavaScript for formatting numbers, all you need is:
function calculateMeter() {
if (feet.innerHTML > 0) {
meter.innerHTML = numberWithCommas*(feet.innerHTML * 0.3048).toFixed(1));
feet.innerHTML = numberWithCommas(feet.innerHTML);
}
}
My function:
function formatNumberWithCommasDec(d) {
d += "";
var c = d.split(".");
var f = c[1];
var a = c.length > 1 ? c[0] + '.' : '.', flag = false;
var g = f.split('').reverse(), y = 1, s = '';
for (var i = g.length - 1; i >= 0; i--) {
flag = false;
var e = g[i];
var h = (y === 3) ? s = s + e + ',' : s = s + e;
console.log(e);
if(y === 3){
y = 1;
flag = true;
} else {
y = y + 1;
}
}
if(flag){
s = s.substring(0, s.length - 1);
} else {
s = s;
}
return a + s;
}
Fiddle: https://jsfiddle.net/6f0tL0ec/1/
Update: found some problems, but everythings good now

How to add spaces separating thousands in Javascript in this example

I have two functions here. One that adds a "," for separating thousands, like 1234 -> 1 234. And one function for increasing.
The function for increasing is just printing 123456 and I would like to combine these, I though I could just change:
$this.html(++current);
to:
$this.html(addSpaces(++current));
But it's not working. Please help me, how can I fix this?
function addSpaces(nStr)
{
nStr += "";
x = nStr.split(".");
x1 = x[0];
x2 = x.length > 1 ? "." + x[1] : "";
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, "$1" + " " + "$2");
}
return x1 + x2;
}
function count($this) {
var current = parseInt($this.html(), 10);
current = current + 13 /* This is increment */
$this.html(++current);
if (current > $this.data("count")) {
$this.html($this.data("count"));
} else {
setTimeout(function() { count($this); }, 100);
}
}
UPDATE I modified your jsfiddle
As current will be parsed again and again from your formatted value, we need to remove spaces from it
current = parseInt(($this.html()).split(' ').join(''), 10)
Also, you need to keep a trace of the string value of the incremented current, under a variable named nextString
You want your number grouped by, at most, 3 digits. The thing is, you may have a remainder if 3 does not divide your string's length. Once you isolate the remainder part of your string (left most) you can group all the others by 3.
DEMO
function addSpaces(nStr)
{
var remainder = nStr.length % 3;
return (nStr.substr(0, remainder) + nStr.substr(remainder).replace(/(\d{3})/g, ' $1')).trim();
}
function count($this) {
var current = parseInt(($this.html()).split(' ').join(''), 10),
nextString = (current+13) + '';
$this.html(addSpaces(nextString));
if (current > $this.data("count")) {
$this.html($this.data("count"));
} else {
setTimeout(function() {
count($this);
}, 100);
}
}
Or You could use things like toLocaleString() if that's what you want :
var number = 3500;
console.log(number.toLocaleString()); // Displays "3,500" if in U.S. English locale
var number = 123456.789;
// German uses comma as decimal separator and period for thousands
alert(number.toLocaleString("de-DE"));
// → 123.456,789
// Arabic in most Arabic speaking countries uses real Arabic digits
alert(number.toLocaleString("ar-EG"));
// → ١٢٣٤٥٦٫٧٨٩
// India uses thousands/lakh/crore separators
alert(number.toLocaleString("en-IN"));
// → 1,23,456.789
// the nu extension key requests a numbering system, e.g. Chinese decimal
alert(number.toLocaleString("zh-Hans-CN-u-nu-hanidec"));
// → 一二三,四五六.七八九
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
alert(number.toLocaleString(["ban", "id"]));
// → 123.456,789
See : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
First one works, and you can use following for second one;
<div class="count">1234</div>
And js;
$(".count").on("click", function() {
$this = $(this);
var current = parseInt($this.html(), 10);
current = current + 13 /* This is increment */
$this.html(++current);
if (current > $this.data("count")) {
$this.html($this.data("count"));
} else {
setTimeout(function() { count($this); }, 100);
}
});
Here is working demo: Demo (Click on first div on demo)

Javascript append to a specific place in an HTML string

I'm building a keypad to enter monetary amounts via touch device.
http://codepen.io/bsley/pen/hrEmK
Once the user has entered 2 digits, I append a decimal. However, once they enter 4 digits, I need to carry the decimal over so it's always 2 digits from the end of the string of numbers.
This way the string always appears as dollars and cents.
I've not been able to find a way to .append X digits from the end of the string in #numBox. Also, even if I was able to, there would need to be someway to search the string for the old decimal and remove it before adding another one digit over to the right.
Any help? Happy to explain further if this isn't concise. Be patient, I'm a total SO noob.
Fixed the issue
if (digits %2 == 0)
{
var mystring = $( "#numBox" ).html();
mystring = mystring.replace('.','');
$( "#numBox" ).html(mystring);
$( "#numBox" ).append(".");
console.log("worked!");
}
Check the updated code on http://codepen.io/bsley/pen/hrEmK
Try this
$(document).ready(function(){
var digits = 0;
var numBox = document.getElementById('numBox');
$('.key').click(function(){
if(this.innerHTML == '0'){
if (numBox.innerHTML.length > 0)
numBox.innerHTML = numBox.innerHTML + this.innerHTML;
digits += 1;
//console.log("digits");
}
else
// add digits
numBox.innerHTML = numBox.innerHTML + this.innerHTML;
digits += 1;
//console.log(digits);
event.stopPropagation();
});
$('.btn').click(function(){
if(this.innerHTML == 'DEL'){
var numBox = document.getElementById('numBox');
if(numBox.innerHTML.length > 0){
// delete a digit
numBox.innerHTML = numBox.innerHTML.substring(0, numBox.innerHTML.length - 1);
digits -= 1;
//console.log(digits);
}
}
else{
// clear numbox
document.getElementById('numBox').innerHTML = '';
digits = 0;
//console.log(digits);
}
event.stopPropagation();
_checkForDecimals();
});
//decimal entry
$('.key').click(function(){
_checkForDecimals();
});
function _checkForDecimals()
{
if (digits > 2) {
var mystring = $( "#numBox" ).html();
mystring = mystring.replace('.','');
var firstPartOfString = mystring.slice(0, mystring.length - 2);
var secondPartOfString = mystring.slice( mystring.length - 2,mystring.length);
//alert(firstPartOfString+'.'+secondPartOfString)
mystring = firstPartOfString+'.'+secondPartOfString;
$( "#numBox" ).html(mystring);
//$( "#numBox" ).append(".");
console.log("worked!");
}
}
});
try something like this
var str = "12.345";
str= str.replace("\.","");
if(str.length > 2){
str = str.substr(0, str.length - 2) + '.' + str.substr(str.length - 2);
}
alert(str);
I checked your fix.But it seems to have an issue.If you press all the keys from 1 to 9, the number becomes 12345678.9. But as per your requirement it should have been 1234567.89 [if I understood correctly].
Please try the below solution and see if it fits your requirement. Please note, at the end of the code block I've added two functions "GetNumberAfterAppendingDecimal" and "GetCleanString" and I've used then on $(.key).click();
$('.key').click(function(){
var inputNumber=GetCleanString($("#numBox").html());
$("#numBox").html(GetNumberAfterAppendingDecimal(inputNumber));
});
function GetNumberAfterAppendingDecimal(str) {
if (str.length < 3)
return str;
var positionFromEnd = 2;
var reversedStr = str.split('').reverse().join('');
if (str.length == 3)
positionFromEnd -= 1;
reversedStr = [reversedStr.slice(0, positionFromEnd), ".", reversedStr.slice(positionFromEnd)].join('');
return reversedStr.split('').reverse().join('');
}
function GetCleanString(str) {
str = str.replace(/[\r]+/, '');
str = str.replace(/[\n]+/, '');
str = str.replace(/[\t]+/, '');
str = str.replace('.', '');
str = $.trim(str);
return str;
}
Very simple, just repleat the code inside $(.key).onclick() for $(div.btn).onclick()..see below :
$('div.btn').click(function(){
var inputNumber=GetCleanString($("#numBox").html());
$("#numBox").html(GetNumberAfterAppendingDecimal(inputNumber));
});

Remove Euro Value and money format with JQuery

I already know how to get a value from a label, the problem is that its showing something like
€123,453.28
I need to remove the eurosign and the commas to be able to make a calculation.
Not remove the decimal point of course
$(document).ready(function () {
$("#TxtVatExcluded").keypress(function () {
var invoicedAmmount = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
alert(invoicedAmmount);
if (invoicedAmmount > 0) {
var ammountWithoutVat = $("#TxtVatExcluded").val();
var result = (ammountWithoutVat / invoicedAmmount) * 100;
$("#OutputLabel").html(result + " %");
}
});
});
"€123,453.28".replace(/[^\d.]/g,"") // Replace every non digit char or dot char
// With an empty string.
Live DEMO
So in your code:
var ammountWithoutVat = $("#TxtVatExcluded").val().replace(/[^\d.]/g,"");
var result = (pareseFloat(ammountWithoutVat, 10) / invoicedAmmount) * 100;

Categories