Reputation: 349
In my database I have phone number as 123-456-7890 and 1234567890, Is there any way to format display in as 123-456-7890
format in my textbox
In my view I have phone textbox as
<input asp-for="PhoneNumber" type="tel" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" readonly class="form-control" id="PhoneNumber" placeholder="">
I need to format all phone number as 123-456-7890
i tried:
function formatPhoneNumber(txt) {
if (String(txt)[3] != "-") {
txt = "" + txt.slice(0, 3) + "-" + txt.slice(3, 6) + "-" + txt.slice(6);
}
return txt;
}
and in my text box
<input asp-for="PhoneNumber" type="tel" readonly pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" onchange="formatPhoneNumber(this)" class="form-control fa-mask" id="PhoneNumber" placeholder="">
Upvotes: 1
Views: 2408
Reputation: 18139
Here is a demo to show how to bind data of Model with format 111-111-1111,and when change the input with the format 111-111-1111. Controller:
public IActionResult Index()
{
TestReadOnly t = new TestReadOnly { PhoneNumber = "1231231234" };
return View(t);
}
View:
@model TestReadOnly
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<input asp-for="PhoneNumber" type="tel" aria-label="Please enter your phone number" placeholder="ex. 111-111-1111" onchange="change()">
@section scripts{
<script type="text/javascript">
$(function () {
//bind the data from Model with format 111-111-1111
let txt = JSON.stringify(@Model.PhoneNumber);
if (String(txt)[3] != "-") {
txt = '' + txt.substring(0, 3) + "-" + txt.substring(3, 6) + "-" + txt.substring(6);
}
$('[type="tel"]').val(txt);
})
//when change the input value,format 111-111-1111
function phoneMask() {
var num = $(this).val().replace(/\D/g, '');
$(this).val(num.substring(0, 3) +'-'+ num.substring(3, 6) + '-' + num.substring(6, 10));
}
$('[type="tel"]').keyup(phoneMask);
</script>
}
Upvotes: 2
Reputation: 149
If you want to call the function you can write <script>formatPhoneNumber("1234567890")</script>
after the input
tag.
note that if you write (this)
in the input
, the parameter is the element itself (in this case, the input
).
So, if you write the (this)
, just change the function a little:
function formatPhoneNumber(el)
{
let txt = el.value; // add this line
if (String(txt)[3] != "-")
{
txt = '' + txt.slice(0, 3) + "-" + txt.slice(3, 6) + "-" + txt.slice(6);
}
//return txt // delete this line
el.value = txt // add this line instead
}
If you don't call the functio via the input
(which means you write <script>formatPhoneNumber(parameter)</script>
), the parameter will be document.getElementById("PhoneNumber")
.
Upvotes: 0