0
我有一個HTML格式的日期對象。Javascript如果無效日期填入空
const start = new Date(document.querySelector('input[name="start"]').value)
如果開始時間留空,我希望返回的值爲空字符串。如何才能做到這一點?
我有一個HTML格式的日期對象。Javascript如果無效日期填入空
const start = new Date(document.querySelector('input[name="start"]').value)
如果開始時間留空,我希望返回的值爲空字符串。如何才能做到這一點?
你可以試試這個代碼:
const value = document.querySelector('input[name="start"]').value
let start = ''
if (value !== '') {
start = new Date(document.querySelector('input[name="start"]').value)
}
你只需要使用它到Date
構造函數之前在輸入值進行檢查:
const start = document.querySelector('input[name="start"]').value !== "" ? new Date(document.querySelector('input[name="start"]').value): "";
演示:
function logIt() {
const start = document.querySelector('input[name="start"]').value !== "" ? new Date(document.querySelector('input[name="start"]').value) : "";
console.log(start);
}
logIt();
<input name="start" type="date" onchange="logIt()" />