2017-10-09 84 views
0

我有一个HTML格式的日期对象。Javascript如果无效日期填入空

const start = new Date(document.querySelector('input[name="start"]').value) 

如果开始时间留空,我希望返回的值为空字符串。如何才能做到这一点?

回答

0

你可以试试这个代码:

const value = document.querySelector('input[name="start"]').value 
let start = '' 
if (value !== '') { 
    start = new Date(document.querySelector('input[name="start"]').value) 
} 
0

你只需要使用它到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()" />