gpt4 book ai didi

javascript - 在输入字段中显示无效日期

转载 作者:行者123 更新时间:2023-11-28 00:43:06 24 4
gpt4 key购买 nike

我正在尝试将默认日期格式更改为 DD/MM/YYYY。我已经成功地做到了这一点。但它显示无效日期。当我选择一个日期时,它运行良好。但是当我清除日期时,它显示无效日期。如何删除此错误消息。

$("input").on("change", function() {
this.setAttribute(
"data-date",
moment(this.value, "YYYY-MM-DD")
.format( this.getAttribute("data-date-format") )
)
}).trigger("change")
input {
position: relative;
width: 150px; height: 20px;
color: black;
}

input:before {
position: absolute;
top: 5px; left: 6px;
content: attr(data-date);
display: inline-block;
color: black;
}

input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button {
display: none;
}

input::-webkit-calendar-picker-indicator {
position: absolute;
top: 16px;
right: 0;
color: black;
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<input type="date" data-date="" placeholder="s" data-date-format="DD/MM/YYYY" name="tckt_issue_date">

最佳答案

更新的答案

您收到无效日期错误的原因是,当您清除日期时,输入将一个空日期传递给您的 jQuery 函数。当值被赋予 moment() 时,它会返回一个错误,因为它需要一个有效的日期。

因此您需要测试一个空值。

工作代码:

$('#datePicker').on('change', function() {

if(this.value){

$(this).attr('data-date', moment(this.value, 'YYYY-MM-DD').format($(this).attr('data-dateformat')));

} else{

$(this).attr('data-date', '');

}

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<input id="datePicker" type="date" data-date="" placeholder="s" data-dateformat="DD/MM/YYYY" name="tckt_issue_date">

此代码还正确更新了 html 中的数据日期属性。

关于javascript - 在输入字段中显示无效日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52270661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com