set maxlength value dynamically in html - javascript

I have input field, with maxlength = 6 and ng-pattern="/^[0-9]{1,6}$/" accepting only numeric values.
On on-blur event I'm formatting the 6 digit code ("123456") to "12-34-56" and browser remembers the formatted value i.e. 12-34-56
next time when I try to auto fill the field using remembered data by browser,
it only fill 4 digits.
How can I fill all the 6 digits. I tried to set the maxlength = 8 when text contains -, but it didn't help.

I prefer solving this kind of issue by rethinking task.
Instead of changing maxLength attribute, change input format. It would be better if user can enter data in "40-15-15" format.

var part1 = document.querySelector("#part1")
var part2 = document.querySelector("#part2")
var part3 = document.querySelector("#part3")
part1.onkeyup = function(el) {
if(isNaN(el.key) && el.key !== "Backspace") {
part1.value = part1.value.slice(0, -1)
}
if (part1.value.length === 2) {
part2.focus()
}
console.log(part1.value + part2.value + part3.value)
}
part2.onkeyup = function(el) {
if(isNaN(el.key) && el.key !== "Backspace") {
part2.value = part2.value.slice(0, -1)
}
if (part2.value.length === 0 && el.key === "Backspace") {
part1.focus()
}
if (part2.value.length === 2) {
part3.focus()
}
console.log(part1.value + part2.value + part3.value)
}
part3.onkeyup = function(el) {
if(isNaN(el.key) && el.key !== "Backspace") {
part3.value = part3.value.slice(0, -1)
}
if (part3.value.length === 0 && el.key === "Backspace") {
part2.focus()
}
console.log(part1.value + part2.value + part3.value)
}
input {
width: 3em;
}
<input type="text" id="part1" maxlength="2" /> -
<input type="text" id="part2" maxlength="2" /> -
<input type="text" id="part3" maxlength="2" />

Related

Replace input value on typing in JS

I have an input with maxLength of 1. I want that if I type another value (key) the current value (letter) that inside the input will be replaced with the new value (letter of key).
I've tried something like that:
container.addEventListener('keyup', function (e) {
var target = e.srcElement || e.target;
var letter = target.value;
var newLetter = letter.replace(/letter/g, letter);
letter.value = newLetter;
});
You can update the value of the input box using this.value and get the key pressed using e.key. This will, however, enter meta keys if pressed:
const container = document.getElementById('container');
container.addEventListener('keyup', function(e) {
this.value = e.key;
});
<input type="text" id="container" maxlength="1" />
The issue with the meta keys could be fixed by checking whether or not e.key is an alphabetic/digit letter by using a regular expression:
const container = document.getElementById('container');
container.addEventListener('keyup', function({key}) {
if(/^[a-z0-9]$/i.test(key)) {
this.value = key;
}
});
<input type="text" id="container" maxlength="1" />
This works for all single character inputs while excluding the space character:
let container = document.getElementById('container');
container.addEventListener('keyup', function (e) {
let valueLength = this.value.length;
if(this.value == " ") {
this.value = "";
return;
}
if(valueLength == 1) {
if( !e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey
&& e.code != "Space" && e.key.length == 1) {
this.value = e.key;
}
}
});
<input id="container" type="text" value="" maxLength="1" />

Allow 2 digit number after the decimal

Hi i am trying to restrict user to input 2 digit number after the decimal.The below functionality is working but i am not able to modify the last two digit.suppose I have entered number 3456.78 and i want to modify 3456.68 it is not allowing.
$('.PMT_AMT').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Here's one possibility that uses a regular expression. Save the old input value on keypress, and if the new value on keyup does not validate, reset to that old value.
You need to validate on keypress as well, because otherwise, if the user types very fast, an invalid value can be saved:
const re = /^\d+(\.\d{0,2})?$/;
let oldVal;
$('.PMT_AMT').keypress(function(event) {
const { value } = this;
if (re.test(value)) oldVal = value;
});
$('.PMT_AMT').keyup(function(event) {
const newVal = this.value;
if (!re.test(newVal)) this.value = oldVal;
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
This solution creates a prediction and tests the regular expression against that instead.
$('.PMT_AMT').keypress(function(event) {
if(!/^\d*(\.\d{0,2})?$/.test(
this.value.slice(0, this.selectionStart)
+ String.fromCharCode(event.which)
+ this.value.slice(this.selectionEnd)
)) event.preventDefault();
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Why use jQuery and not just browser functionality?
<input type="number" step="0.01">
On submit the browser will check if the submitted value of the input field has maximum two decimals.

html Input type number with Thousand Separator

i want to add thousand separator on keyup event in input type number
but this work just in 6 character, if more than 6 character, value on input has reseted
this my short code
<input type="number" id="tanpa-rupiah" step="any">
var dengan_rupiah = document.getElementById('dengan-rupiah');
dengan_rupiah.addEventListener('keyup', function(e)
{
dengan_rupiah.value = formatRupiah(this.value, 'Rp. ');
});
function formatRupiah(bilangan, prefix)
{
var number_string = bilangan.replace(/[^,\d]/g, '').toString(),
split = number_string.split(','),
sisa = split[0].length % 3,
rupiah = split[0].substr(0, sisa),
ribuan = split[0].substr(sisa).match(/\d{1,3}/gi);
if (ribuan) {
separator = sisa ? '.' : '';
rupiah += separator + ribuan.join('.');
}
rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
return prefix == undefined ? rupiah : (rupiah ? 'Rp. ' + rupiah : '');
}
this my fiddle https://jsfiddle.net/C2heg/4619/
This might suit you. On keydown prevent the default action if it is not a number key. On keyup, parse the value and update it. Use the data- attributes to store and get the original value.
var elem = document.getElementById("num");
elem.addEventListener("keydown",function(event){
var key = event.which;
if((key<48 || key>57) && key != 8) event.preventDefault();
});
elem.addEventListener("keyup",function(event){
var value = this.value.replace(/,/g,"");
this.dataset.currentValue=parseInt(value);
var caret = value.length-1;
while((caret-3)>-1)
{
caret -= 3;
value = value.split('');
value.splice(caret+1,0,",");
value = value.join('');
}
this.value = value;
});
function showValue()
{
console.log(document.getElementById("num").dataset.currentValue);
}
<input type="text" id="num" maxlength="30">
<button onclick="showValue()">Get Value</button>
Ok I have posted answer below. I have added limit of 20 numbers. You can change it as per your need.
You can use Number.toLocaleString() for this purpose.
Below is working example:
// When ready.
$(function() {
var extra = 0;
var $input = $("#amount");
$input.on("keyup", function(event) {
// When user select text in the document, also abort.
var selection = window.getSelection().toString();
if (selection !== '') {
return;
}
// When the arrow keys are pressed, abort.
if ($.inArray(event.keyCode, [38, 40, 37, 39]) !== -1) {
if (event.keyCode == 38) {
extra = 1000;
} else if (event.keyCode == 40) {
extra = -1000;
} else {
return;
}
}
var $this = $(this);
// Get the value.
var input = $this.val();
var input = input.replace(/[\D\s\._\-]+/g, "");
input = input ? parseInt(input, 10) : 0;
input += extra;
extra = 0;
$this.val(function() {
return (input === 0) ? "" : input.toLocaleString("en-US");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="amount" name="amount" type="text" maxlength="20" />
change your the input type equal to "text" then its work
<input type="text" id="tanpa-rupiah" step="any">
checkout jsfiddle

Custom mask for phone numbers

I am using the jsmask plugin to mask telephone numbers.
The requirements are
It can have optional + at the start
It can have spaces in between
I tried this
$('#Telephone').mask('+0000000 000 000 0000', { reverse: true });
but it aint accepting optional plus.
Is there an inbuilt format or can we have a custom format for it
Please advise.
That's impossible.
You can add optional parameters only in end of the input.
They have an open pull request in Github.
You can check it here.
Following code is working, you can try it.I have created solution in JSfidller for you. check it if you want.
HTML:
<form id="example-form" name="my-form">
<label>Phone number:</label><br />
<input id="phone-number" name="phone-number" type="text" maxlength="21" placeholder="+XXXXXXX XXX XXX XXXX" /><br /><br />
<input type="button" value="Submit" />
</form>
Script:
$('#phone-number', '#example-form')
.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
// Adding blankspace in 9th, 13th and 17th position.
//Change it according to your need
if (key !== 8 && key !== 9) {
if ($phone.val().length === 8) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 12) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 16) {
$phone.val($phone.val() + ' ');
}
}
// Allow numeric number and tab, backspace, delete keys only.
//Change it according to your need
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('+'); // as your phone number start with '+'
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '+') {
$phone.val(''); // if somebody type '+' it will be vanish
}
});

Restrict input field to two decimals with jQuery

I have an input field which I want to restrict so that the user only can input a number with the maximum of two decimals. Want to do this using jQuery.
Could I use jQuery toFixed() function somehow?
Thanx!
An alternative approach with a regular expression:
$('#id').on('input', function () {
this.value = this.value.match(/^\d+\.?\d{0,2}/);
});
The id selector can be replaced by a css selector.
$('input#decimal').blur(function(){
var num = parseFloat($(this).val());
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
if(num/cleanNum < 1){
$('#error').text('Please enter only 2 decimal places, we have truncated extra points');
}
});
Here is a fiddle http://jsfiddle.net/sabithpocker/PD2nV/
Using toFixed will anyhow cause approximation 123.6666 -> 123.67
If you want to avoid approximation check this answer Display two decimal places, no rounding
A HTML5 solution:
<input type="number" step="0.01" />
Demo
If you want to style invalid inputs (some browsers do it by default), you can use :invalid selector:
input:invalid { box-shadow: 0 0 1.5px 1px red; }
Note this approach won't attempt to truncate the number automagically, but if the user enters more than two decimal digits, the input will become invalid, and thus the form won't be submitted:
<input type="text" name="amount1" id="amount1" class="num_fld Amt" onkeypress="return check_digit(event,this,8,2);" size="9" value="" maxlength="8" style="text-align:right;" />
The following function will restrict decimals according to your need of decimal places and also restrict more than one dot
function check_digit(e,obj,intsize,deczize) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) { keycode = e.which; }
else { return true; }
var fieldval= (obj.value),
dots = fieldval.split(".").length;
if(keycode == 46) {
return dots <= 1;
}
if(keycode == 8 || keycode == 9 || keycode == 46 || keycode == 13 ) {
// back space, tab, delete, enter
return true;
}
if((keycode>=32 && keycode <=45) || keycode==47 || (keycode>=58 && keycode<=127)) {
return false;
}
if(fieldval == "0" && keycode == 48 ) {
return false;
}
if(fieldval.indexOf(".") != -1) {
if(keycode == 46) {
return false;
}
var splitfield = fieldval.split(".");
if(splitfield[1].length >= deczize && keycode != 8 && keycode != 0 )
return false;
}else if(fieldval.length >= intsize && keycode != 46) {
return false;
}else {
return true;
}
}
}
$("#myInput").focusout(function() {
if ($(this).val().length > 2 || isNaN(Number($(this).val())) {
alert("Wrong number format");
}
});
Try this for all symbols:
inputField.value.replace(/(\...)(.)/, "$1");
or this for numbers:
inputField.value.replace(/(\.[0-9][0-9])([0-9])/, "$1");
I found this method here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Example:_Switching_words_in_a_string
<input type="text" id="decCheck" onkeyup="decimalCheck();"/>
<script>
function decimalCheck(){
var dec = document.getElementById('decCheck').value;
if(dec.includes(".")){
var res = dec.substring(dec.indexOf(".")+1);
var kl = res.split("");
if(kl.length > 1){
document.getElementById('decCheck').value=(parseInt(dec * 100) /
100).toFixed(2);
}
}
}
</script>
A similar solution with a backspace hit on reaching more than 2 decimal places.
function limitDec(id) {
// find elements
var amt = $("#testdec")
// handle keyup
amt.on("keyup", function() {
if (isNaN(amt.val())) {
amt.val(0);
}
if (amt.val().indexOf(".") > -1 && (amt.val().split('.')[1].length > 2)) {
amt.val(amt.val().substring(0, amt.val().length - 1));
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="text" id="testdec" onkeyup="limitDec(this.id)" />

Categories

Resources