About this snippet

Improve your checkout form with auto-formatting. This script automatically adds spaces after every four digits as the user types their card number, which makes it much easier to read and prevents errors.

Size
1.5 KB
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
394
<div class="card-input-wrapper">
  <label>Card Number</label>
  <div class="input-box">
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect><line x1="1" y1="10" x2="23" y2="10"></line></svg>
    <input type="text" id="ccInput" placeholder="0000 0000 0000 0000" maxlength="19">
  </div>
</div>
.card-input-wrapper {
  font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  max-width: 350px;
  margin: 0 auto;
}
label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #374151;
}
.input-box {
  position: relative;
  display: flex;
  align-items: center;
}
.input-box svg {
  position: absolute;
  left: 12px;
  color: #9ca3af;
}
input {
  width: 100%;
  padding: 12px 12px 12px 45px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 1.1rem;
  font-family: monospace;
  outline: none;
  transition: border-color 0.2s;
  box-sizing: border-box;
}
input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
const ccInput = document.getElementById("ccInput");

ccInput.addEventListener("input", function(e) {
  // Remove all non-digits
  let value = e.target.value.replace(/\D/g, "");
  
  // Add space every 4 digits
  value = value.replace(/(\d{4})(?=\d)/g, "$1 ");
  
  e.target.value = value;
});
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save