Reputation: 68
I want to Arrange my input (phone number) value according to below format
<input type="text" value="123-456-7890">
if type 1234567890 it will set like 123-456-7890
Upvotes: 0
Views: 1924
Reputation: 5513
var $phone=1234567890
$phone.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
Output:
123-456-7890
Edit:
Updated JsFiddle with keyup
Output in a div - Phone number hardcoded
http://jsfiddle.net/smileyface/mu95g83n/
Output in a div
http://jsfiddle.net/smileyface/mu95g83n/17/
Output inside textbox itself
http://jsfiddle.net/smileyface/mu95g83n/20/
$(document).ready(function() { //Run when document is ready (page loaded)
$('#txtval').keyup(function count() { //on every key up inside textbox
var $input = this.value;
if ($input.length == 3) {
$('#txtval').val($input + "-"); //add hiphen to input after 3 letters
}
if ($input.length == 7) {
$input = $input.replace(/(\d{3})(\d{3})/, "$1-$2")
$('#txtval').val($input + "-"); //add hiphen after 7 letters
}
if ($input.length == 11) {
$input = $input.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3")
$('#txtval').val($input); //show phone number as expected
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Enter Phone# : <input type="text" id="txtval" maxlength="12" />
Upvotes: 2
Reputation: 125
$("input").keyup(function() {
var length = 0;
length = $('#txtval').val().length;
if (length == 3 || length == 7) {
$('#txtval').val($('#txtval').val().concat('-'));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Phone: <input type="text" id="txtval" value="" placeholder="Enter your Phone" />
Upvotes: 2