I want to give space in between number just for displaying like this
I used
phone.addEventListener("keyup", function(){
txt=this.value;
if (txt.length==3 || txt.length==7)
this.value=this.value+" ";
});
but this code is working only for input type text, the problem with this is, the length of the input is not considering as 10.
.
Is there any solution, with which it will be displayed with spaces, the length must be 10, and with type number, and in back-end it should be saved without spaces?
I want to give space in between number just for displaying like this
I used
phone.addEventListener("keyup", function(){
txt=this.value;
if (txt.length==3 || txt.length==7)
this.value=this.value+" ";
});
but this code is working only for input type text, the problem with this is, the length of the input is not considering as 10.
.
Is there any solution, with which it will be displayed with spaces, the length must be 10, and with type number, and in back-end it should be saved without spaces?
Share Improve this question edited Sep 16, 2021 at 15:39 Randy Casburn 14.2k1 gold badge19 silver badges32 bronze badges asked Sep 16, 2021 at 15:34 N SARATH CHANDN SARATH CHAND 1692 silver badges11 bronze badges 5-
1
Rather than using
type="number"
, usetype="pattern"
, constrain the input to digits only and ensure spaces exist via regexp. Your code can still then put in spaces and constraint will pass. – Randy Casburn Commented Sep 16, 2021 at 15:42 - 1 You should use maskjs libraries like imask.js for quick solution. Or you can try stackoverflow./questions/40513950/… – Alaksandar Jesus Gene Commented Sep 16, 2021 at 15:42
- 1 Just to clarify - you want the spaces to be put in automatically but are they to be ignored if for example the user backspaces to delete some digits, or positions the cursor part way along the string? You are adding spaces to the actual string which means that although they haven't typed them they must be aware of them when they want to delete things. Could this be rather confusing? Would it be better to have them visible but not in the string they are editing? – A Haworth Commented Sep 16, 2021 at 15:48
- can you include a working snippet of your html/css/js so that we can help you modify it? – tstrand66 Commented Sep 16, 2021 at 15:49
- @AHaworth, exactly I need user to do backspace just in case if he has mistaken somewhere. Okay, rather than adding in the string, how can we visually add space in between the numbers? – N SARATH CHAND Commented Sep 17, 2021 at 6:02
3 Answers
Reset to default 2Example solution using the pattern
input type with simple regexp that ensures only numbers, correct spacing, and submits only numbers without spaces to the server.
Your code does breaks down if the user inputs spaces themselves, so the JavaScript has been enhanced to ensure the correct format.
- Ignore the input of spaces and any input beyond 12 characters by preventing the default behavior (ignore the keystroke):
if ((txt.length == 12 || e.which == 32) & e.which !== 8) e.preventDefault();
(Literally "if 12 characters OR keypress is spacebar AND key is not the backspace key" then ignore the keypress)
- Add spaces automatically (as your code did):
if ((txt.length == 3 || txt.length == 7) && e.which !== 8)...
NOTE: in both cases, if the backspace key is pressed, then allow that key to work (keycode 8).
- When the form is submitted, remove any spaces from the "phone" input so the server only receives the numbers.
document.getElementById("phone").addEventListener("keydown", function(e) {
const txt = this.value;
// prevent more than 12 characters, ignore the spacebar, allow the backspace
if ((txt.length == 12 || e.which == 32) & e.which !== 8) e.preventDefault();
// add spaces after 3 & 7 characters, allow the backspace
if ((txt.length == 3 || txt.length == 7) && e.which !== 8)
this.value = this.value + " ";
});
// when the form is submitted, remove the spaces
document.forms[0].addEventListener("submit", e => {
e.preventDefault();
const phone = e.target.elements["phone"];
phone.value = phone.value.replaceAll(" ", "");
console.log(phone.value);
//e.submit();
});
<form>
<input id="phone" name="phone" type="pattern" placeholder="### ### ####" pattern="[\d]{3} [\d]{3} [\d]{4}">
<input type="submit">
</form>
You can do a string replace before submitting the string to the backend:
number_str = this.value.replace(" ","");
let number_number = parseInt(number_str);
//backend request stuff
You can also use a hidden input to store the unspaced string and a visible one for the spaced one and just update them both? You would only submit the hidden one.
<input id="phonenumber" type="text" />
<input id="secret-phonenumber" type="hidden" />
It's slightly tricky to decide exactly what the user interface should be. Although they can see the spaces they can't delete them, which if the normal browser editing were allowed they would be able to do.
We also want to ignore non-digit input and not allow the total number of digits to go beyond 10.
This snippet does these things by having the input as type normal text rather than number and testing each key input to see if it should be included or not and rewriting the value each time with the spaces inserted if required.
const phone = document.querySelector('.phone');
phone.addEventListener("keyup", function(e) {
let txt = this.value.replace(/\D/g, '');
let newtxt = '';
//now copy the number inserting a space where needed
for (let i = 0; i < Math.min(txt.length, 10); i++) {
newtxt += txt[i];
if ((i == 2) || (i == 5)) {
newtxt += ' ';
}
}
if (newtxt[newtxt.length - 1] == ' ') newtxt = newtxt.substring(0, newtxt.length - 1);
this.value = newtxt;
});
<input class="phone">
There needs to be further thought as to whether some refinements to the user interface would be a good idea. For example:
- re-positioning the cursor (at the moment it goes to the end of the string after each input which the user maybe won't expect if they are editing part way along the number)
- and it's probably a moot point as to whether it is best to show briefly a character that is illegal, to sort of reassure the user they have indeed pressed a key, or whether that character should never show.
Before submitting the value to the backend, remember to remove the spaces:
phone.value.replace(/\D/g, '');