html - 清除本地日期时间和必需的

标签 html frontend datetimepicker datetime-local

我在 HTML5 中遇到日期时间本地选择器问题。我想使用清除按钮清除日期时间,但这是不可能的,因为输入中的“必需”功能不允许。我将通过一段代码来查看差异。一种是有要求的,一种是没有要求的。您知道如何保留“必需”并清除从 ex:“15/03/2022 00:00 AM”到 mm/dd/yyyy --:-- -- 的输入。 谢谢。

label {
    display: block;
    font: 1rem 'Fira Sans', sans-serif;
}

input,
label {
    margin: .4rem 0;
}
    <input type="datetime-local" name="start_timestamp" id="start_timestamp" required>


<label for="meeting-time">Choose a time for your appointment:</label>

<input type="datetime-local" id="meeting-time"
   name="meeting-time">

最佳答案

所需的属性负责是否显示重置按钮。如果设置了 required,则必须以编程方式解决重置问题。您可以使用 yourDateElement.valueAsDate = nulldatetime-local 类型执行此操作。

const clearBtn = document.getElementById('clear-btn');
clearBtn.addEventListener('click', () => {
  const d =   document.getElementById('start_timestamp');
  d.valueAsDate = null
})
label {
    display: block;
    font: 1rem 'Fira Sans', sans-serif;
}

input,
label {
    margin: .4rem 0;
}
<input type="datetime-local" name="start_timestamp" id="start_timestamp" value="" required>

<button id="clear-btn" onclick="clear()">clear</button>


<label for="meeting-time">Choose a time for your appointment:</label>

<input type="datetime-local" id="meeting-time"
   name="meeting-time">

也适用于 Chrome

const clearBtn = document.getElementById('clear-btn');
clearBtn.addEventListener('click', () => {
  const d =   document.querySelector('input[type=datetime-local]');
  d.value = 0
})
label {
    display: block;
    font: 1rem 'Fira Sans', sans-serif;
}

input,
label {
    margin: .4rem 0;
}
<input type="datetime-local" name="start_timestamp" id="start_timestamp" value="" required>

<button id="clear-btn" onclick="clear()">clear</button>


<label for="meeting-time">Choose a time for your appointment:</label>

<input type="datetime-local" id="meeting-time"
   name="meeting-time">

关于html - 清除本地日期时间和必需的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71483409/

相关文章:

php - 在页面加载时运行 javascript

javascript - 使用 HTML5 FileWriter truncate() 方法?

javascript - 当我滚动到它时,如何将元素的 id 传递给 url?

javascript - <span> 不能作为 <select> 的 child 出现在 react 中

html - 背景模式和下拉菜单冲突

.net - 如何检索 DateTimePicker 的下拉状态?

html - 防止文本在 div 中换行,但并非没有

jquery - jqGrid不显示任何数据

javascript - 无法使用 ui-router 从 url 栏更改状态

c# - 从字符串(日期和时间)设置日期时间选择器