What is the best method to modify the accurate phone number within my script?

I need help with a text format script.

link

HTML CODE:

<label for="primary_phone">Primary Phone Number<span class="star">*</span></label>
<br>
<input type="text" name="primary_phone" id="primary_phone" class="_phone required-input"  value=""  maxlength="10">

CSS CODE:

.invalid{
    border:1px solid red !important;
}
.valid{
    border:1px solid green !important;
}

JS CODE:

function phoneFormat(){
    $( "._phone" ).on('blur change', function() {
        text = $(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
        var testt=$(this).val().match(text);

        if($(this).val()=='' || $(this).val().match(text) || $(this).val().length == 0)
        {
            $(this).removeClass('valid').addClass('invalid');
        }
        else{

            $(this).removeClass('invalid').addClass('valid');
        }
        $(this).val(text);
    });
}

 $( "#primary_phone" ).blur(function() {
        phoneFormat();
    });

The script formats the text like this:

1234567890

Which appears as:

(123) 456-7890

The issue arises when trying to edit the phone number, due to maxlength="10"

I want the user to be able to input up to 10 characters. How can I achieve both requirements?

If anything is unclear, I will provide more details in an update. Thank you!

Answer №1

To ensure only numbers are entered in the input box, simply remove any special characters when focusing on it:

  $("#primary_phone").on("click", function() {
   var thisVal = $(this).val();

    var value = thisVal.replace(/[^\/\d]/g,'');
    $(this).val(value);


});

Now, when you click out of the input box, your original formatting function for the number will take effect :)

Check out the working example here: https://jsfiddle.net/reko91/gto0qeyx/2/

Answer №2

To enhance the character limit, it's recommended to increase the maxlength attribute to a higher value like 15. You can then link the input field to the keypress event.

Within this event, you have the option to compare the keyCode with a predefined set of acceptable values and prevent the entry of characters that are not included in this list.

Additionally, consider restricting the inclusion of digits when there are already 10 present, except for cases where the user has selected a part of the input containing numbers.

var alwaysAllowed = [32, 40, 41, 45]; // [" ","(",")","-"]

function keyCode(keyCode) {
    if (alwaysAllowed.indexOf(keyCode) !== -1) {
        return "allowed";
    } else if (keyCode >= 48 && keyCode <= 57) {
        // 0 - 9
        return "number";
    } else {
        // any other character
        return false;
    }
}

function countNumbers(text) {
    var counter = 0;
    for (var i = 0; i < text.length; i++) {
        if (parseInt(text[i]) >= 0 && parseInt(text[i]) < 10) {
            counter++;
        }
    }
    return counter;
}

$primaryPhone.on("keypress", function () {
    var keyCodeEvaluation = keyCode(event.keyCode);
    if (keyCodeEvaluation === false) {
        event.preventDefault();
    } else if (keyCodeEvaluation === "number") {
        var value = this.value,
            counter = countNumbers(value.substring(this.selectionStart, this.selectionEnd));
        
        if (counter === 0 && countNumbers(value) > 9) {
            event.preventDefault();
        }
    }

});

This method enables users to modify or input phone numbers while maintaining the specified format.

OF UTMOST IMPORTANCE

You must revamp your phoneFormat() function.

With each execution, an additional event listener is attached. The initial time the input value is modified, it triggers once. Subsequently, it executes twice, thrice, and so forth.

Moreover, it's advisable to store frequently used objects in variables to optimize performance, such as $(this) (repetitively creating the same jQuery object can impact performance).

Here's a functional example that addresses most common scenarios.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Use `$$state: {…}` within the request rather than the data

When attempting to send a request with data, I am only getting "f {$$state: {…}}" in the console. $scope.createTask = function () { var req = $http.post('api/insert', { title: $scope.newTitle, description: ...

Tips for fixing ReferenceError: Cookies is undefined

Currently, I'm configuring a modal that will be hidden once the user submits their request. if ( Cookies.get("submitted") && JSON.parse(Cookies.get("submitted")) ) { $("#booking-form-modal").hide(); return true; error page ...

Steer clear of using grey backgrounds for anchors/links in IE 10

What is the best way to prevent the irritating grey background that appears on anchors in IE 10 when they are clicked? ...

Using Javascript to retrieve form data from a separate file

I am struggling with my HTML and JavaScript files to collect data. Despite my efforts, the function is not executing properly. Below is the code I have been working on: HTML File : <form class="form-newsletter"> <div class="form-group"> ...

What is the best way to input data into the verified full name box?

.html file executed code <input type="name" [(model)]="x.name" class="form-control" pattern="[a-z]" > Greetings to the members of Stack, I am in need of assistance. I am relatively new to Angular and I am looking for a way to validate the full nam ...

The ckeditor vanishes upon refreshing the div element

I have created two pages named openclosediv.php and content.php. The openclosediv.php page contains a list of records and a button that can show/hide the div, bringing in the content from content.php. However, I am facing an issue where the CKEditor in the ...

Issue with getStaticProps not updating fetched values in Next.js production environment

I am currently working on building a blog using Next.js. Since the back-end is taken care of by another team, I am utilizing fetch API calls in getStaticProps to retrieve my articles, even though it may be considered best practice to interact with the data ...

"Implementing a Texture as Material in Three.js: Step-by-Step Guide

I recently discovered Three.js and I'm really enjoying it. As a newcomer to JavaScript, I'm eager to delve deeper into animation and related topics. //UPDATE I've been working on this code snippet, but unfortunately, it's not functioni ...

Vue JS console displays an error stating "the <li> tag is missing a closing tag."

Below is the code snippet I am currently using to change the color based on the character's name: I encountered an error indicating that the li tag was not properly closed, although it appears to be closed. However, there seems to be an issue during ...

React Native ScrollView ref issue resolved successfully

I'm trying to automatically scroll to the bottom of a flatlist, so here's what I have: const scrollViewRef = useRef(); //my scroll view <ScrollView ref={scrollViewRef} onContentSizeChange={() => { scrollViewRef.current.scr ...

Is there a way to exclude the Unicode character from the first menu item while still utilizing it in the other items on my menu?

I have been working on customizing my menu by using the unicode character \25C6 to represent a black solid diamond as a spacer between labels. After searching for solutions on Stack Overflow, I attempted to implement the suggested method using the bef ...

The excessive use of Selenium Webdriver for loops results in multiple browser windows being opened simultaneously, without allowing sufficient time for the

Is there a way to modify this code so that it doesn't open 150 browsers to google.com simultaneously? How can I make the loop wait until one browser finishes before opening another instance of google? const { Builder, By, Key, until } = require(& ...

Controlling a complex IF statement with jQuery

Currently, I have an if statement with over 100 different conditions. Right now, I am using a structure similar to this... $('select').on("change",function(){ if( $(this).val() === 'tennis' ) { $('.sport').val( ...

JavaScript image sorting function fails to sort multiple ID elements that match

Currently, I am working on a project to develop an image sorter using toggle buttons. However, I have encountered an issue where my function is only effective for the first image ID and not any others. Below is the JavaScript function in question: functi ...

Loading options dynamically in a dropdown list using KnockoutJS

I am new to KnockoutJS and I have successfully worked with static data in dropdown lists. Now, I need to dynamically populate the dropdown list from a controller. 1. I want to retrieve a dynamic list from my controller and populate it in a dropdown list. ...

What is the proper way to justify text alignment in HTML?

I want to align the text to the right like the first row, but the second row keeps overflowing below the image. How can I ensure that the text is properly aligned regardless of the number of rows? <a href="javascript:;" id="A_3"><i id="I_4">&l ...

What is the best approach to integrating AJAX calls with promises in the Angular framework?

I'm facing an issue while using Angular promises with the $q service in my controller. Here's the code snippet: var myController = function ($scope, myService) { $scope.doSomething = function (c, $event) { $event.preventDefault(); ...

Discover the magic of Material UI's Multiple Select feature for working with arrays

Utilizing the material-ui multiple select feature, I have set up a demo following the guidelines provided in the Multiple Select documentation. You can check out my example here: codesandbox In my demonstration, I am aiming to use 2 arrays for two separa ...

HTML5 for advanced positioning and layering of multiple canvases

I have 2 canvas layers stacked atop each other, but I need to position them relative to the entire page. The dimensions of both layers are fixed at a width of 800 and a height of 300. My goal is to center the canvas layers regardless of screen size, with ...

Is it possible to achieve a smooth transition to the right using CSS

I'm attempting to create a sliding box effect from left to right using only transitions, similar to this: #box { width: 150px; height: 150px; background: red; position:absolute; transition: all 2s ease-out; right:auto; } .active{ bac ...