Issue regarding the slash format in credit card expiration dates

When entering the credit card expiration date, I am currently facing an issue. Every time I input two numbers, I need to manually add a slash (/) after them. However, if I try to delete the third number, it only removes one character. Is there a way to make it so that when I delete the third number, the slash is also removed? Please help, thank you.

var characterCount
$('#expiry').on('input', function(e) {
  if ($(this).val().length == 2 && characterCount < $(this).val().length) {
    $(this).val($(this).val() + '/');
  }
  characterCount = $(this).val().length
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="expiry" type="text" />

Answer №1

using vanilla JavaScript

const expiryInput = document.querySelector('#expiry')

expiryInput.onkeydown = function() {

  const key = event.keyCode || event.charCode;
  
  if (key !== 8 && key !== 46 ) {
    if (inp.value.length == 2) {
        inp.value= (inp.value+'/');
    }
  }
  
  if (( key == 8 || key == 46 ) && inp.value.length === 4) {
    inp.value = inp.value.slice(0,3)
  }    
};
<input id="expiry" type="text" />

Answer №2

To enhance the functionality, you can include another keyup event that detects when the backspace key is pressed and then removes any trailing slash at the end of the input value.

I also suggest setting the maxlength, pattern, and inputmode attributes on the input element.

var characterCount;
$('#expiry').on('input', function(e) {
  if ($(this).val().length == 2 && characterCount < $(this).val().length) {
    $(this).val($(this).val() + '/');
  }
  characterCount = $(this).val().length
}).on('keyup', function(e) {
  if (e.which === 8) {
    $(this).val($(this).val().replace(/\/$/, ''))
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="expiry" type="text" maxlength="5" pattern="^\d{2}/\d{2}$" inputmode="numeric" />

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

Store various dropdown selections in an array

Questions are being generated from a database for users to answer using a drop-down menu. Upon selecting a specific option, a suggestion is added to an array triggering a JavaScript on-change event. Once all questions are answered, the array including all ...

I'm having trouble using Discord.js to set up a custom role with specialized permissions for muting users

module.exports = { name: "mute", description: "This command is used to mute members in a server", execute: async function (msg, arg) { const muteRole = await msg.guild.roles.cache.find((r) => r.name == "Mute ...

The addEventListener feature in Bootstrap 5.2.3 seems to be malfunctioning

I have a sample page with a Bootstrap dialog being returned from the server. I want to display it inside a DIV. However, when clicked, I receive this error: Uncaught TypeError: myModal.addEventListener is not a function It points to this line of code: ...

Navigate to a specific moment in an HTML5 audio track by clicking on the progress bar

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <script> $(document).ready(function(){ var counter = 0; ...

Utilizing React hooks to dynamically toggle a class within a component

While similar questions have been raised previously, none seem to address my specific issue. Most references involve class components that do not align exactly with what I am attempting to achieve. My goal is to toggle two components on and off with a simp ...

A step-by-step guide on effectively swapping out every element in an array with its corresponding index location

After pondering over this question and conducting a search to see if it has been asked before, I couldn't quite find the answer due to difficulty in phrasing my inquiry. In case this question has already been addressed, I apologize for any duplication ...

When you click on the text, the calendar will pop up for you to

When the text "SetExpiryDate" is clicked, a date picker opens. After selecting a date, the text changes to "Expires ${date}" where the selected date is inserted. If no date is selected, the text remains as it is. I'm curious how I can implement this ...

Converting an ajax request to CORS

Would appreciate some guidance on accessing an API through my localhost using the code below: $.ajax({ url: "http://domain.xxx.net/api/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7a3b8bcb2b9a4f9bda4b8b9e8b2ba ...

Ways to retrieve textStatus beyond ajax boundaries

Do you know how to access the textStatus variable after an ajax call? I need to use this variable in an if condition. Can anyone provide assistance? $this->registerJs("colorArray = ['#ff4c4c','#32CD32']; $('.grooveTable&apo ...

Is there a feature similar to Nuxt.js' auto-register in Next.js?

My Journey as a Beginner Being a beginner in the tech world, specifically in full-stack development (although I'm about 8 years behind), I find myself grappling with the decision of what to focus on learning. Vue and Nuxt.js are fantastic technologi ...

Assist me in minimizing redundant code in a basic jQuery function

I successfully created a carousel using the jQuery cycle plugin with 4 links that correspond to different slides. Currently, I have separate blocks of code for each link, but I'm looking to optimize by creating a single function. $('#features-sl ...

Customize the CSS for material-ui buttons or create a new style altogether

Looking to customize the background color of a material UI RaisedButton, I have encountered a challenge. This is what I currently have: const style = { backgroundColor: 'green' }; export default class CreateLinksave extends React.Component { ...

Express: SimpleAuth

I've been attempting to set up basic authorization for the endpoints in my express app using express-basic-auth, but I keep getting a 401 unauthorized error. It seems like the headers I'm sending in Postman might be incorrect: Middleware: app.u ...

Display items in a not predetermined order

Despite its simplicity, I am struggling to get this working. My aim is to create a quiz program using JavaScript. Here is the basic structure: <ul> <li>option1</li> <li>option2</li> <li>option3</li> </ul> &l ...

Deactivate background hover effects for bar charts in Recharts

Is there a way to disable the gray background that appears when hovering over bar charts in Recharts? I'm using version 1.4.1 and my code looks like this: import React from "react" // Recharts import { Bar, BarChart, CartesianGrid, ResponsiveContain ...

The scrolling action triggered by el.scrollIntoViewIfNeeded() goes way past the top boundary

el.scrollIntoViewIfNeeded() function is used to scroll to element el if it's not within the visible browser area. Although it generally works well, I have encountered some issues when trying to use it with a fixed header. I have provided an example s ...

What is the correct placement for $.validator.setDefaults({ onkeyup: false }) in order to deactivate MVC3 onKeyup for the Remote attribute?

After coming across various solutions on how to disable the onKeyup feature of MVC3 Remote Validator, I noticed that many suggest using the following code: $.validator.setDefaults({ onkeyup: false }); However, I'm in a dilemma about where to place t ...

An error is thrown when using less.js

Every time I attempt to add less.js, I encounter an XmlHttpRequest Exception 101. Including the .less file is done using this method: <link rel="stylesheet/less" type="text/css" href="anything.less" /> This issue only arises when I upload the th ...

Guide to refreshing the modal component with updated properties

In my application, I have created a modal component for managing recipes. This modal allows users to save recipes to a list. let modal = <Modal saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/> However, I also want to utilize the same m ...

Is there a quicker alternative to the 500ms delay caused by utilizing Display:none?

My div is packed with content, including a chart from amCharts and multiple sliders from noUiSlider. It also features various AngularJS functionalities. To hide the page quickly, I use $('#container').addClass('hidden'), where the rule ...