What is the best way to adjust the layout of a card number when entering it?

Check out the sample I have here:

link

Here's the HTML code:

<input type="text" name="card_number" id="card_number" class="disbaled_cc required-input valid" maxlength="16" placeholder="xxxx-xxxx-xxxx-xxxx">

And this is the JS code:

function cardFormat(){
    var format_card = $(this).val().replace(/(\d{4})(\d{4})(\d{4})(\d{4})/, "$1-$2-$3-$4");
    if ($(this).val() == '' || $(this).val().match(format_card) || $(this).val().length == 0) {
        console.log("invalid");
    }else{
        console.log("valid");
    }
}

$("#card_number").on('blur change', function () {
        cardFormat();
    });

I'm looking to modify the user input in a specific format like so:

For instance, when the user types this:

1234567891091234 ---> 1234-5678-9109-1234

If the user enters and formats correctly, it should remain as such:

1234-5678-9109-1234 ---> 1234-5678-9109-1234

In this scenario, the issue arises with having 19 characters (max should be 16). How do you suggest we solve this challenge?

If anything is unclear, please let me know for further clarification.

Could you provide feedback on the functionality of my code?

Thank you in advance!

Answer โ„–1

The issue lies with $(this), which is not referring to the intended element, instead it refers to window, and you are failing to assign a new value.

Make the following change:

function formatCard() {
  if ($(this).val().length > 4 && $(this).val().indexOf('-') === -1) {
    var formattedCard = $(this).val().replace(/(\d{4})(\d{4})(\d{4})(\d{4})/, "$1-$2-$3-$4");
    $(this).attr('maxlength', 16);
    $(this).val(formattedCard);
    if ($(this).val() == '' || $(this).val().match(formattedCard) || $(this).val().length == 0) {
      console.log("invalid");
    } else {
      console.log("valid");
    }
  } else {
    $(this).attr('maxlength', 19);
  }
}

$("#card_number").on('input blur', formatCard); //<--use the function as a callback.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="card_number" id="card_number" class="disbaled_cc required-input valid" maxlength="16" placeholder="xxxx-xxxx-xxxx-xxxx">


Alternatively, you can pass the element into the function:

function formatCard($el) { // <---get the element here $el refers to $(this)
  if ($el.val().length > 4 && $el.val().indexOf('-') === -1) {
    var formattedCard = $el.val().replace(/(\d{4})(\d{4})(\d{4})(\d{4})/, "$1-$2-$3-$4");
    $el.attr('maxlength', 16);
    $el.val(formattedCard);
    if ($el.val() == '' || $el.val().match(formattedCard) || $el.val().length == 0) {
      console.log("invalid");
    } else {
      console.log("valid");
    }
  } else {
    $el.attr('maxlength', 19);
  }
}

$("#card_number").on('blur change', function() {
  formatCard($(this)); // <----pass the element here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="card_number" id="card_number" class="disbaled_cc required-input valid" maxlength="16" placeholder="xxxx-xxxx-xxxx-xxxx">

Answer โ„–2

Enhanced: Experiment with various characters such as a-Z or numbers to ensure validity. Any spaces and hyphens will be automatically removed.

$('.wrapper').on('input', 'input[name="code"]', formatCode);

function formatCode() {

  var $input = $(this);
  var $check = $input.parent().find('.check');
  
  $input.val($input.val().replace(/ /g, '')); // eliminates all spaces
  $input.val($input.val().replace(/-/g, '')); // deletes all entered dashes
  $input.val($input.val().replace(/(\d{4})(\d{4})(\d{4})(\d{4})/, "$1-$2-$3-$4")); // your validation
  var check = $input.val().match(/-/g) || [];  
  
  if($input.val().length === parseInt($input.attr('maxlength')) && check.length === 3) {
  $check.html("valid");
  return false;
  }
  
  $check.html('invalid'); 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <p>
    Our objective: 1111-1111-1111-1111<br>
  </p>
  <input name="code" maxlength="19">
  <span class="check"></span>
</div>

Answer โ„–3

function formatNumber(value, splitLimit, separator='-') {
  const regExRule = RegExp(String.raw`(.{${splitLimit}})`, 'g')
  const formatted = value.replace(regExRule, `$1${separator && separator}`);
  return formatted
}


console.log( "Formatted number with space ๐Ÿ‘‰ ",
  formatNumber("44771133778855", 5, ' ')
)

console.log("Formatted number with dash ๐Ÿ‘‰ ",
  formatNumber("44771133778855", 4, '-')
)

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

What is the best way to add bind-attr class to an existing class in Ember framework?

Is there a way to add a dynamic CSS class onto an initial static one using the {{bind-attr}} method? The problem I am facing is that when there is a static initial class, the dynamic class does not get added when the page loads. However, once I change the ...

A guide on calculating character count in a text area where certain characters are counted twice (javascript)

Is there a way to accurately count the characters in a textarea field, taking into account special characters like "รฉ, รจ, โ‚ฌ, ..." which should count as two characters? This is important for sending SMS messages where character limits are crucial, as so ...

The supported browser is unable to import ES6 modules

Attempting to incorporate moment.js as an es6 module. The most recent version of Chrome is being utilized. Referring to the conversation here, I experimented with the src path (es6) import * as moment from './node_modules/moment/src/moment' A ...

"Enhancing User Experience with Hover States in Nested React Menus

I have created a nested menu in the following code. My goal is to dynamically add a selected class name to the Nav.Item element when hovering, and remove it only when another Nav.Item is hovered over. I was able to achieve this using the onMouseOver event. ...

Is there a way to make sure that my submit button aligns perfectly with the text beneath it

I am new to coding and I need help aligning my submit button with the text "You can contact Armando through his freelance portfolio on Upwork by clicking...". Can anyone assist me with this? .topnav { background-color: #333; overflow: hidden; } .to ...

Opening a modal in React Material UI from an autocomplete component results in losing focus

My current challenge involves utilizing the material-ui library to create an autocomplete feature where each item is clickable and opens a modal window. The basic structure looks like this: const ModalBtn = () => { ... return ( <> ...

An error has occurred due to a connection timeout with the net.Socket

I have been attempting to send text to my network printer using a tcp connection. function print(buf2){ var printer = new net.Socket(); printer.connect(printer_port, printer_name, function() { console.log('Connected'); printe ...

Struggling with implementing jquery Ajax and a php script to fetch information from a mysql database

I'm encountering issues with my current web app project in displaying a simple jpg image based on the selected radio button using jQuery AJAX along with a PHP script to interact with MySQL. Below is my ajax.js file: $('#selection').change( ...

How can we prevent the issue of text and banner complications when they overlap?

My website has a banner that scrolls down with you, but whenever it hits text, the text covers the banner. How can I fix this issue and make sure the banner stays on top? https://i.sstatic.net/FsDZI.jpg here is the code snippet in question: <!DOCTYPE ...

Using CSS to create a background color gradient

As I work on my website, I am experimenting with a background that transitions from one color to another. The colors I am using are #87a0b4 and #6a86a0. I have encountered two issues: Firstly, the transition is not displaying correctly on Internet Explor ...

Repeated attempts to initiate ajax script failing to function

I am completely new to the world of Ajax, having just started learning about it a few days ago. Despite my lack of experience, I need to incorporate it into a form that I am creating for my employer. Unfortunately, I have been facing difficulties in getti ...

Suggestions for resolving the "Undefined" problem in my JQuery Ajax web service request

Below is the JavaScript code I've written: function testService(test) { var data = "{param2:\"" + test + "\"}"; $.ajax({ type: "POST", url: "WebService1.asmx/HelloWorld", dataType: "json", data: data, contentType: "appli ...

I'm curious if there is a method to incorporate localStorage into the initialState of Redux Toolkit within Next.js 14

Attempting to establish the initial value of a Redux Toolkit slice for dark mode using localStorage is proving problematic in Next.js, as the window object is not defined on the server-side, resulting in errors. The typical workaround involves using if (t ...

Developing real-time chat functionality in React Native with node.js and Socket.io

I'm on the lookout for resources to help me navigate both server-side (mostly) and client-side development. I recently came across a resource called Simple Real Time chat app but unfortunately, it did not yield significant results. I tried locally ho ...

Select certain properties from an object using JavaScript

I am looking to extract a specific subset of values from an object in a specific order. const obj = { a: 1, b: 2, c: 3, d: 4 }; const values = extractValues(obj, ['a', 'd']); // extracted values [1, 4] While I can create my own extrac ...

Creating a user-friendly interface for the admin to easily upload photos by implementing a php/bootstrap/js code within the panel

I'm currently in the process of creating an online website as part of my thesis project. I've been researching this specific code, but unfortunately, I haven't been able to find a solution. In the admin section of the site, I need to enable ...

Use the inline IF statement to adjust the icon class depending on the Flask variable

Is it feasible to achieve this using the inline if function? Alternatively, I could use JavaScript. While I've come across some similar posts here, the solutions provided were not exactly what I expected or were implemented in PHP. <i class="f ...

Utilize JavaScript to Trigger AJAX HoverMenuExtender in .NET

Within my C# web application, I am attempting to trigger an Ajax HoverMenuExtender using JavaScript, rather than relying on hovering over a designated control. When I set the TargetControlID of the HoverMenuExtender to a control on the page and hover ove ...

CSS Hack for Internet Explorer 7 Fix

Dealing with styling in IE7 can be quite challenging, especially when working within a WebCenter Portal application where conditional statements cannot be used to load specific stylesheets. Instead, skins are utilized, which are essentially CSS files. Is ...

Is there a way to have this <a> link trigger a postback to my ASP.NET method when clicked?

Is there a way for me to trigger a postback to my method when I click on a specific link? <li runat="server" onclick="log_out" > <a onclick="log_out" runat="server" href="LogIn.aspx" ><i class="icon_key_alt"></i> Log Out</a& ...