How to style a credit card expiration date input field to include spaces and forward slash?

12,065

Solution 1

Read first few characters and save them to the variable. then read last characters, and write them into other variable... Then concatenate with the space between them.

How can I get last characters of a string using JavaScript

Retrieve first 2 characters of this.title attribute, and call corresponding id

Or, have 2 fields and style them with CSS to look like a single field.

Solution 2

You can accomplish this using two inputs fields, removing the border of the input fields, adding a border to a wrapper element to appear as one input and a place / in between like so. - jsFiddle Demo

HTML

 <span class="expiration">
    <input type="text" name="month" placeholder="MM" maxlength="2" size="2" />
    <span>/</span>
    <input type="text" name="year" placeholder="YY" maxlength="2" size="2" />
</span>

CSS

.expiration {
    border: 1px solid #bbbbbb;
}
.expiration input {
    border: 0;
}

Result

input field data slash

This is just the CSS needed to demonstrate the idea, of course you can style it however you'd like.

I used <span>s because they are inline elements, as are input fields.

Share:
12,065
Doug
Author by

Doug

Updated on June 14, 2022

Comments

  • Doug
    Doug almost 2 years

    I am wondering how I can style one input field (type = text) to display with spaces and a slash between numbers, like this:

    Credit card expiry field

    I know how to constrain the input to digits and perform validation. That's not what I'm asking. I'm wondering about the actual display. Can you use CSS to do this somehow, splitting the first two MM digits from the last two YY digits?

    I want the user to be able to type 4 digits only and have it display as: MM / YY

    (Different question from How to format credit card input fields and expiry date. That question focuses on validation.)

  • Devin
    Devin over 9 years
    well, I didn't see because I was answering the question. Anyway, what's the problem? as you can see I'm resetting styles which you aren't, I didn't know you were the owner of CSS
  • Doug
    Doug over 9 years
    Choosing this as it answers my question about getting the desire result with a single input field. It took a surprising amount of code for something this simple, but many corner cases had to be covered. Posting for posterity: jsfiddle.net/nirodhasoftware/pgfcpxeb
  • Kushagra Agarwal
    Kushagra Agarwal over 5 years
    @Doug this fails to work in android chrome as keydown will always written keycode as 229 or 0
  • Zac Grierson
    Zac Grierson over 2 years
    I dont see a jquery tag so could you provide this in javascript?