DatePicker点击后重置表单输入框与选择框问题求助
Hey there! Let's break down why your form fields keep resetting when you click the DatePicker input, and fix this issue step by step.
最常见的原因:表单默认提交行为被触发
If your DatePicker input is wrapped inside a <form> tag, clicking it (or even elements from the DatePicker dropdown) might accidentally trigger the form's default submit action. When the form submits, the page refreshes, and all your input/select fields revert back to their initial load state—this is a super common gotcha!
解决方法:阻止表单默认提交
Add a listener to your form to stop the default submit behavior (you can still add custom submit logic later if you need it):
$('form').on('submit', function(e) { e.preventDefault(); // Add your custom form submission code here if needed });
其他可能的原因与修复方案
1. 事件冒泡引发的意外操作
The click event from the DatePicker might be bubbling up to a parent element that's triggering a form reset. Stop the event bubble directly on your DatePicker input:
$('.myClassDate').on('click', function(e) { e.stopPropagation(); });
2. 重复初始化或脚本冲突
Make sure your DatePicker initialization runs only once, after the DOM is fully loaded. Wrap it in $(document).ready() to avoid unexpected reinitializations:
$(document).ready(function() { $('.myClassDate').datepicker({ format: "yyyy-mm-dd", todayBtn: 'linked', todayHighlight : true, autoclose: true }); });
Also, double-check if there are other scripts on the page that call form.reset() accidentally when clicking elements—search your codebase for any reset logic that might be firing unexpectedly.
内容的提问来源于stack exchange,提问作者Cesar Wahyu

