如何将 html 日期选择器最大日期设置为等于今天

问题描述 投票:0回答:1

我遇到一种情况,用户只能输入今天之前的日期。 请问最简单的方法是什么?

html
1个回答
0
投票

你也必须使用js,这是一个例子:

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Date Picker</title>
    </head>
    <body>
        <label for="datePicker">Select a date:</label>
        <input type="date" id="datePicker" max="" />
    
        <script>
            // Get today's date
            const today = new Date();
            const formattedDate = today.toISOString().split('T')[0];
            
            // Set the max attribute
            document.getElementById('datePicker').setAttribute('max', formattedDate);
        </script>
    </body>
    </html>
© www.soinside.com 2019 - 2024. All rights reserved.