3
<input name="textfield" type="text" id="textfield" value="6267973685" /> Enter number like this and in next field it will display like this <input name="textfield2" type="text" id="textfield2" value="(626) 797-3685" /> 

I want this to be done using JavaScript i had tried this a lot but not find any success please help me in it.

2

2 Answers 2

1

You can use this nice light weight plugin Masked input plugin for the jQuery

$("#textfield").mask("(999) 999-9999");
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="//digitalbush.com/wp-content/uploads/2014/10/jquery.maskedinput.js"></script> <input name="textfield" type="text" id="textfield" value="6267973685" /> <br/> Enter number like this and in next field it will display like this <br/> <input name="textfield2" type="text" id="textfield2" value="(626) 797-3685" />

Sign up to request clarification or add additional context in comments.

Comments

1

Try using oninput , onfocus event , String.prototype.replace() with RegExp /(^\d{3})/ to match first three digits , /(\s\d{3,3})(?!-{1}|$)/ to match three digits following space character not followed by "-" or end of input string ; setting maxlength attribute to 14 at input type="text" element

var input = document.querySelector("input[name=textfield]"); input.oninput = input.onfocus = function() { this.value = this.value .replace(/(^\d{3})/, "($1) ") .replace(/(\s\d{3,3})(?!-{1}|$)/, "$1-") } input.focus()
<form> <input name="textfield" type="text" id="textfield" value="6267973685" maxlength="14" /> <input type="reset" /> </form>

2 Comments

can we change on focus to on click
@Harsimransingh "can we change on focus to on click" Yes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.