onchange事件触发后输入框内容丢失问题求助
onchange Event Let's break down why your input is clearing out and fix it step by step:
1. The Immediate Issue: Code Execution Order
Take a close look at your dateFunction code—there's a critical order problem:
function dateFunction(event){ var bla=$("#inpCalendarDate").val(); console.log(bla); event.preventDefault(); return false; // This line stops ALL further code from running! $("#inpCalendarDate").val("test"); // This line never gets executed }
The return false; statement sits before you try to set the input's value to "test". Once the function hits that return, it stops cold, so your value assignment never runs at all. That's why your input stays blank.
2. Quick Fix: Reorder Your Code
First, move the value assignment before the return statement so it actually executes:
function dateFunction(event){ var inputVal = $("#inpCalendarDate").val(); console.log(inputVal); // Set the value first $("#inpCalendarDate").val("test"); // Then handle event prevention and return event.preventDefault(); return false; }
3. Additional Check: Date Picker Interference
If the input still clears after fixing the code order, it’s likely the date picker plugin (indicated by the datePickerBar__input class) is overriding the value after your onchange event fires. Here’s how to work around that:
- Use the date picker’s built-in event callbacks (most plugins like jQuery UI Datepicker have an
onSelectoption) instead of relying on the nativeonchange. - If you need to stick with
onchange, wrap your value assignment in a shortsetTimeoutto ensure it runs after the date picker’s internal logic:function dateFunction(event){ var inputVal = $("#inpCalendarDate").val(); console.log(inputVal); event.preventDefault(); return false; // Delay the assignment to outrun the date picker's default behavior setTimeout(() => { $("#inpCalendarDate").val("test"); }, 10); }
4. Cleaner Alternative: jQuery Event Binding
For better maintainability, ditch the inline onchange and bind the event with jQuery instead:
$(document).ready(function() { $("#inpCalendarDate").on("change", function(event) { var inputVal = $(this).val(); console.log(inputVal); $(this).val("test"); event.preventDefault(); return false; }); });
Then remove the inline onchange from your input tag:
<input type="text" placeholder="Select your arrival date..." class="input__input datePickerBar__input " id="inpCalendarDate"/>
That should resolve the issue where your input’s content disappears after the onchange event fires.
内容的提问来源于stack exchange,提问作者user2395176

