-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
71 lines (61 loc) · 1.98 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Masking</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#date-input {
width: 150px;
padding: 5px;
font-size: 16px;
text-align: center;
}
</style>
</head>
<body>
<div>
<label for="date-input">Enter Date (YYYY/MM/DD):</label>
<input type="text" id="date-input" maxlength="10" placeholder="YYYY/MM/DD">
</div>
</body>
<script>
$(document).ready(function () {
const dateInput = $('#date-input');
// Function to format the date as YYYY/MM/DD
function formatDate(value) {
const numbers = value.replace(/\D/g, ''); // Remove non-numeric characters
const year = numbers.substring(0, 4);
const month = numbers.substring(4, 6);
const day = numbers.substring(6, 8);
let formattedDate = year;
if (month) formattedDate += '/' + month;
if (day) formattedDate += '/' + day;
return formattedDate;
}
// Handle input event to enforce masking
dateInput.on('input', function () {
let value = $(this).val();
const formattedValue = formatDate(value);
$(this).val(formattedValue);
});
// Allow backspace to remove characters properly
dateInput.on('keydown', function (e) {
if (e.key === 'Backspace') {
let value = $(this).val();
const newValue = value.slice(0, -1); // Remove the last character
$(this).val(formatDate(newValue));
e.preventDefault(); // Prevent default backspace behavior
}
});
// Prevent entering invalid characters
dateInput.on('keypress', function (e) {
const char = String.fromCharCode(e.which);
if (!/[0-9]/.test(char)) {
e.preventDefault(); // Allow only numbers
}
});
});
</script>
</html>