How to mask phone number as 123-456-7890? - javascript

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="">

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>
}
result:

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").

Related

how to get the values from input fields dynamically

i have a page in my website that has a form that conatains inputs fields, i also have a button that creates more input fields incase the user needs to inputs more things. the problem now is that if the user makes a mistake and creates inputs feilds that he/she doe not need he can remove them but this creates a problem when inserting the value of the input fields in the database. i am using a for loop to get all the value of the input fields by id eg. id1, id2, id3 etc, but if the user removes one of the inputs field for example id2, i cant get id3 becuase the for loop will still run normally from 1 too the end and will not skip 2.
here is the code to create more input feilds:
let counter = 1;
document.getElementById("shownew").addEventListener("click", (e) => {
e.preventDefault();
// new_section.style.display = "flex";
new_section.insertAdjacentHTML('beforeend',
` <div class="lowerlayer2" id="close${counter}">
<button id="delete" onclick="deleteme(${counter})"><i class="fa fa-minus"></i></button>
<input type="text" placeholder="Word Type" id="wtype${counter}" />
<input type="text" placeholder="Synonym" id="syn${counter}" />
<input type="text" placeholder="Antonyms" id="anty${counter}" />
<textarea
cols="30"
rows="10"
placeholder="History & Etymology"
id="history${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Examples"
id="example${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Definition 1"
id="def1${counter}"
></textarea>
</div>`
);
counter++;
});
here is the code to delete the input feilds:
function deleteme(id) {
document.getElementById(`close${id}`).style.display="none";
document.getElementById(`close${id}`).innerHTML="";
counter--
}
here is the code to get the values from the values of input fields:
document.getElementById("wan").addEventListener("click", (e) => {
e.preventDefault();
type = "";
syn = "";
anty = "";
history = "";
example = "";
def1 = "";
for (let i = 0; i < counter; i++) {
type += document.getElementById(`wtype${i}`).value + "^";
syn += document.getElementById(`syn${i}`).value + "^";
anty += document.getElementById(`anty${i}`).value + "^";
history += document.getElementById(`history${i}`).value + "^";
example += document.getElementById(`example${i}`).value + "^";
def1 += document.getElementById(`def1${i}`).value + "^";
}
console.log(
type +
" . " +
syn +
" . " +
anty +
" . " +
history +
" . " +
example +
" . " +
def1
);
});

using .on to listen for event not working

I am trying to use .on to listen for an event.
html:
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
</div>
JS:
for (n = 1; n < inputLength+3 ; ++n) {
var test2 = document.getElementById(dude+n);
$(test2).on('change', '#group_names', forFunction);
}
The change to the input field is not being recognized.
Additionally, I am hoping .on will recognize changes made to new html i am injecting using the following function:
var dude = "name";
function forFunction() {
for (m = 1; m < inputLength + 1; ++m) {
var test = document.getElementById(dude + m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder=" + dude + (m + 1) + " id=" + dude + (m + 1) + " name=" + dude + (m + 1) + "><br>";
document.getElementById('group_names').insertAdjacentHTML('beforeend', txt);
//function updateHTML(txt)
}
}
}
I am not sure if my syntax for .on is correct. I am trying to use "#group_names" as the selector, but not sure if I am doing it right.
Thanks
You probably want to use event delegation on the parent div instead.
$('#group_names').on('change', 'input.form-control.name', forFunction);
Consider the following jQuery code.
$(function() {
var inputFields = $("input[id*='name']");
function forFunction(evt) {
console.log(evt.type);
inputFields.each(function(i, el) {
var n = i + 1;
if ($(el).val() != "") {
console.log("Value Detected");
$("<input>", {
type: "text",
class: "form-control name",
placeholder: "group" + n,
id: "group" + n,
name: "group" + n
}).insertBefore("#group_names");
}
});
}
inputFields.on("change", forFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name="name1"><br>
</div>
This should work for all of the Input items.

how to serialize a form under specific conditions

Taka a look at this fiddle here this is a form where a business user enters the offered services.I sent the data with ajax and by serializing the form.
Click edit and add(plus sign) a service...in the example an input is added where it's name attribute value is of this **form= form[5]...**contrast with this with the form of the name attribute value in the other inputs...only the newly added services have the name attribute like this and the reason for that is to serialize only these...and not the others already present in the DOM/stored in the DB.
And now my problem:
Imagine that the user goes to edit the already registered services(or that he goes to edit them and add a new one)...at this case the already registered services wont'be serialized cause of the form the name attribute value has...(and the reason for this is explained above).
What can I do in this case?Sometimes I must serialize only part of a form and sometimes whole of the form.If all the inputs have name attribute value of form[1....] then along with the newly added input...already registered services will be serialized again.
Thanks for listening.
Code follows(you can see it in the fiddle too)
$('.editservices').click(function() {
//console.log(('.wrapper_servp').length);
originals_ser_input_lgth = $('.services').length;
var originals = [];
$('.show_price')
// fetch only those sections that have a sub-element with the .value
class
.filter((i, e) => $('.value', e).length === 1)
// replace content in remaining elements
.replaceWith(function(i) {
var value = $('.value', this).data('value');
var fieldsetCount = $('#serv').length;
var index = fieldsetCount + i;
return '<div class="show_price"><p id="show_p_msg">Price
visibility</p></div>' + '\
<div class="show_p_inpts">' +
'<input class="price_show"' + (value == 1 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="1">yes' +
'<input class="price_show"' + (value == 0 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="0">no' +
'</div>'; // HTML to replace the original content with
});
$('#buttons').removeClass('prfbuttons');
$('#saveserv').addClass('hideb');
$('.actionsserv').removeClass('actionsserv');
priceavail = $(".price_show:input").serializeArray();
});
$('#addser').on('click', function() {
$('#saveserv').css('border','2px solid none');
var serviceCount = $('input.services').length + 1;
var serv_inputs = '<div class="wrapper_servp"><div class="serv_contain">\n\
<input placeholder="service" class="services text" name="form[' + serviceCount + '][service]" type="text" size="40"> \n\
<input placeholder="price" class="price text" name="form[' + serviceCount + '][price]" type="text" size="3"></div>';
var p_show = '<div class="show_p">' +
'<p id="show_p_msg">Price visibility;</p>' +
'<span id="err_show_p"></span><br>' +
'</div>';
var inputs = '<div class="show_p_inpts">' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="1">yes' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="0">no' +
'</div></div>';
$('.wrapper_servp').last().after(serv_inputs + p_show + inputs);
$('#saveserv').removeClass('hideb');
$('#remser').css('display', 'inline');
});
$('#cancelserv').click(function(e) {
e.preventDefault();
//var newinputs = $('.wrapper_servp').length;
//var inp_remv = newinputs - originals_ser_input_lgth;
//$('.wrapper_servp').slice(-inp_remv).remove()
$('.show_p_inpts')
.filter((i, e) => $('.price_show:checked', e).length === 1)
.replaceWith(function(i) {
var value = $('.price_show:checked').attr('value');
return '<span data-value="' + value + '" class="value">' + (value == 1 ? "yes" : "no") + '</span>'
});
});
var groupHasCheckedBox = function() {
return $(this).find('input').filter(function() {
return $(this).prop('checked');
}).length === 0;
},
inputHasValue = function(index) {
return $(this).val() === '';
};
$('#saveserv').click(function(e) {
e.preventDefault();
//from here
var $radioGroups = $('.show_p_inpts');
$('.show_p_inpts').filter(groupHasCheckedBox).closest('div').addClass("error");
$('.services, .price').filter(inputHasValue).addClass("error");
//to here
var $errorInputs = $('input.services').filter((i, e) => !e.value.trim());
if ($errorInputs.length >= 1) {
console.log($errorInputs);
$('#err_message').html('you have to fill in the service'); return;
}
if ($('input.price').filter((i, e) => !e.value.trim()).length >= 1) {
$('#err_message').html('you have to fill in the price'); return;
}
});
var IDs=new Array();
$('body').on('click', '#remser', function(e){
var inputval=$('.services:visible:last').val();
if(inputval!=='')
{r= confirm('Are you sure you want to delete this service?');}
else
{
$('.wrapper_servp:visible:last').remove();
}
switch(r)
{
case true:
IDs.push($('.services:visible:last').data('service'));
$('.wrapper_servp:visible:last').addClass('btypehide');
if($('.serv_contain').length==1)$('#remser').css('display','none');
$('#saveserv').removeClass('hideb').css('border','5px solid red');
//originals.servrem=true;
break;
case false:var i;
for(i=0;i<originals.ser_input_lgth;i++)
{
$('input[name="service'+i+'"]').val(services[i].value);
$('input[name="price'+i+'"]').val(prices[i].value);//εδω set value
}
$('.services').slice(originals.ser_input_lgth).remove();
$('.price').slice(originals.ser_input_lgth).remove();
$('.openservices').addClass('hide').find('.services,.price').prop('readonly', true);
var text='<p class="show_price">Θες να φαίνεται η τιμή;<span data-value="'+ show_pr_val.value +'" class="value">' +(show_pr_val.value==1 ? 'yes':'no') + '</span></p>';
$('.show_p_inpts').remove();
$('.show_price').replaceWith(text);;
break;
}
});
I have an Idea for you. What you can do is when you show the currently existed value in you html instead of giving name attribute just give data-name attribute. I.e
Change this
<input class="services text" data-service="21" size="40" value="hair" type="text" name="service0" readonly="">
To This
<input class="services text" data-service="21" size="40" value="hair" type="text" data-value="hair" data-name="service0" readonly="">
Now when user update this values you can bind an event in jQuery like below.
$(document).ready(function(){
$(".services input").on("change paste keyup", function() {
if($(this).val() === $(this).attr("data-value"))
{
$(this).removeAttr("name");
}else{
$(this).attr("name",$(this).attr("data-name"));
}
});
});
By this way you can give name attribute to only those elements whose values are changed. Now each time you can serialize the whole form and it will only get the value of changed elements.
Don't forget to give unique class to already existed elements so you can bind on change event. Hope its clear to you.

JavaScript For Loop Round Form Input Fields

I'm currently working on creating an expenses form and am writing a function to validate the entered data.
I allow for 6 expense amounts to be entered and a description on each and onClick of the submit button I am trying to write a for loop that will loop round the amount fields, check if they are numeric and, if they are, then check to ensure a description has been entered.
The form basically looks like:
<form action="##" name="myForm" id="myForm" method="post">
<input type="text" name="otherExpenseDesc1" id="otherExpenseDesc1">
<input type="text" name="otherExpenseAmount1" id="otherExpenseAmount1">
<input type="text" name="otherExpenseDesc2" id="otherExpenseDesc2">
<input type="text" name="otherExpenseAmount2" id="otherExpenseAmount2">
<input type="text" name="otherExpenseDesc3" id="otherExpenseDesc3">
<input type="text" name="otherExpenseAmount3" id="otherExpenseAmount3">
<input type="text" name="otherExpenseDesc4" id="otherExpenseDesc4">
<input type="text" name="otherExpenseAmount4" id="otherExpenseAmount4">
<input type="text" name="otherExpenseDesc5" id="otherExpenseDesc5">
<input type="text" name="otherExpenseAmount5" id="otherExpenseAmount5">
<input type="text" name="otherExpenseDesc6" id="otherExpenseDesc6">
<input type="text" name="otherExpenseAmount6" id="otherExpenseAmount6">
<input type="submit" name="formSubmitBtn" value="SUBMIT" onClick="checkForm();">
</form>
And the javascript I have at the moment is:
function checkForm() {
var errMsg = "";
var otherExpense1 = document.getElementById('otherExpenseAmount1').value;
var otherExpenseDesc1 = document.getElementById('otherExpenseDesc1').value;
var otherExpense2 = document.getElementById('otherExpenseAmount2').value;
var otherExpenseDesc2 = document.getElementById('otherExpenseDesc2').value;
var otherExpense3 = document.getElementById('otherExpenseAmount3').value;
var otherExpenseDesc3 = document.getElementById('otherExpenseDesc3').value;
var otherExpense4 = document.getElementById('otherExpenseAmount4').value;
var otherExpenseDesc4 = document.getElementById('otherExpenseDesc4').value;
var otherExpense5 = document.getElementById('otherExpenseAmount5').value;
var otherExpenseDesc5 = document.getElementById('otherExpenseDesc5').value;
var otherExpense6 = document.getElementById('otherExpenseAmount6').value;
var otherExpenseDesc6 = document.getElementById('otherExpenseDesc6').value;
for (i=1; i<7; i++) {
expenseNo = 'otherExpense' + i;
expenseDescNo = 'otherExpenseDesc' + i;
if (expenseNo != "") {
if (isNaN(expenseNo)) {
alert(expenseNo + ' is not a number');
errMsg = errMsg + 'The amount must be a number.<br />';
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
} else {
alert('otherExpenseAmount' + i + ' is a number');
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
}
}
}
if (errMsg != "") {
showDialog('alert', 'OK', '', errMsg, '');
}
}
When I'm submitting the form with valuesin a couple of the fields it still displays an alert for each otherExpenseAmount item saying that it is not numeric, although it is, and the border style doesn't change.
Any idea where I'm going wrong?
You're trying to access a variable with a string. You should change your code to utilise arrays, something like this:
jsFiddle
function checkForm() {
var errMsg = "";
var otherExpense = [];
otherExpense.push(document.getElementById('otherExpenseAmount1').value);
otherExpense.push(document.getElementById('otherExpenseAmount2').value);
otherExpense.push(document.getElementById('otherExpenseAmount3').value);
otherExpense.push(document.getElementById('otherExpenseAmount4').value);
otherExpense.push(document.getElementById('otherExpenseAmount5').value);
otherExpense.push(document.getElementById('otherExpenseAmount6').value);
// 0-based index for arrays
for (i=0; i<6; i++) {
if (otherExpense[i] != "") {
if (isNaN(otherExpense[i])) {
alert('otherExpense ' + (i + 1) + ' is not a number (=' + otherExpense[i] + ')');
errMsg = errMsg + 'The amount must be a number.<br />';
document.getElementById('otherExpenseAmount' + (i + 1)).style.border = '2px sold #990000';
} else {
alert('otherExpenseAmount' + (i + 1) + ' is a number');
document.getElementById('otherExpenseAmount' + (i + 1)).style.border = '2px sold #990000';
}
}
}
if (errMsg != "") {
alert(errMsg);
//showDialog('alert', 'OK', '', errMsg, '');
}
return false;
}
Your problem is on these lines; you're setting the border to be the same, regardless of the condition (easy mistake to make).
if (isNaN(expenseNo)) {
alert(expenseNo + ' is not a number');
errMsg = errMsg + 'The amount must be a number.<br />';
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
// -----------------------------------------------------------------------------^^^^^^
} else {
alert('otherExpenseAmount' + i + ' is a number');
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
// -----------------------------------------------------------------------------^^^^^^
}
Suggestion
I hate to be that guy.
Have you considered adopting jQuery? It's perfectly designed for tasks such as this.
Utilising methods such as filter and simple selectors, it's easy to determine whether all inputs fulfil your requirements. Here's an example:
// select all inputs with a class of "number"
// then filter those inputs, selecting only those where the value is "not a number"
// if there is a length, i.e. more than 0 were found, alert a message
if ($('input.number').filter(function() { return isNaN(this.value); }).length) {
alert('Please ensure all numbers are valid');
}
This would obviously require you to make small amendments to your HTML, by adding the number class to the required elements, but it's a small sacrifice to make.
jsFiddle demo

View page does not recognize null element in load

I have an javascript function that generates links in my page based on a DropDown. I'm checking the javascript function in two places; when the DropDown changes with attribute "onchange", and when the page is loaded. The error is generated when the page is loaded without element on viewbag, my javascript is not recognizing the null element for generate links without the information on viewbag.
<p>Pesquisar por: #Html.DropDownList("tipoPesquisa", ViewBag.DropDownPesquisa as SelectList, new { onchange = "alteraFiltro()" })
<div id="dadosFornecedor">
#if (ViewBag.CurrentFornecedor != null)
{
<fieldset>
<legend>#ViewBag.CurrentFornecedor.RazaoSocial</legend>
<b>Razão Social:</b> #ViewBag.CurrentFornecedor.RazaoSocial <b>Endereço:</b> #ViewBag.CurrentFornecedor.Endereco
#Html.Hidden("idFornecedor", new { IdFornecedor = ViewBag.CurrentFornecedor.IdFornecedor })
<input type="button" class="btn" onclick="removerFornecedor();" value="Remover Fornecedor" />
<br />
<br />
</fieldset>
<br />
}
</div>
<script type="text/javascript">
$(function () {
alteraFiltro();
});
function removerFornecedor() {
var div = $("#dadosFornecedor");
var hidden = $("#idFornecedor");
div.empty();
div.append("<input type='hidden' name='deletarFornecedor' value='true' />")
}
function alteraFiltro() {
var urlCodigo = $("#linkCodigo");
var urlLancamento = $("#linkLancamento");
var urlPagamento = $("#linkPagamento");
var urlFornecedor = $("#linkFornecedor")
var dropValue = $("#tipoPesquisa").val();
var hidden = $("#idFornecedor");
if (hidden.val() == "" || hidden.val() == null || hidden == null) {
urlCodigo.attr("href", "saidasDiversas?sortOrder=#ViewBag.CodigoSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlLancamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataLancamentoSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlPagamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataPagamentoSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlFornecedor.attr("href", "saidasDiversas?sortOrder=#ViewBag.FornecedorSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "")
} else{
urlCodigo.attr("href", "saidasDiversas?sortOrder=#ViewBag.CodigoSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlLancamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataLancamentoSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlPagamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataPagamentoSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlFornecedor.attr("href", "saidasDiversas?sortOrder=#ViewBag.FornecedorSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "")
}
}
</script>
If the issue is caused by ViewBag.CurrentFornecedor not having a value when the view is first loaded, try altering your javascript along these lines:
var hidden = $("#idFornecedor");
if (hidden.val() == "" || hidden.val() == null || hidden == null) {
// ...
}
else {
urlCodigo.attr("href", "saidasDiversassortOrder=#ViewBag.CodigoSortParm&idFornecedor="
+ #{ViewBag.CurrentFornecedor != null ? ViewBag.CurrentFornecedor.IdFornecedor : -1}
+ "&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
// ...
}

Categories

Resources