问题
I have datepicker
<input type='text' class='inp'>
<script>
$('.inp').datepicker();
$(".inp").on("change",function (){
console.log('inp changed');
});
</script>
When I first change '.inp' manually type there a value, then immediately I click on datepicker's opened calendar. I get two 'change' event listeners. First from manual change, then from datepicker change. How can I avoid this?
回答1:
Set your input readOnly
, it will help you to change the value of field through icon only.
<input type='text' class='inp' readOnly />
then use onSelect
to get selected date, as following:
$(function() {
$(".inp").datepicker({
onSelect: function(dateText, inst) {
// alert(dateText);
}
});
});
回答2:
Try using the onSelect function like:
$(function() {
$( ".datepicker" ).datepicker({
onSelect: function() {
//your code here
}});
This will be fired when they select a date from the calendar not when they are typing.
回答3:
You can have onSelect trigger the change event on the text field. This way editing the date via the text box or via the date picker behave the same.
$('.inp').datepicker({
onSelect: function() {
return $(this).trigger('change');
}
);
$(".inp").on("change",function (){
console.log('inp changed');
}
回答4:
If you are using the bootstrap datepicker you can do the following:
$('.datepicker').datepicker()
.on('changeDate', function(e){
# `e` here contains the extra attributes
});
For more details view: Bootstrap Datepicker events
回答5:
Thanks! Everybody, but I could not make field readonly one, this is requirement. So I had to reasearch myself. So I posting my final solution. I did unbinding for 150 ms, then bind again. I made a jquery plugin for this
function myfunc(that){
$(that).one('change', function(){
var that = this;
setTimeout(function(){myfunc(that);}, 150);
//some logic
}
)
}
myfunc(".inp");
回答6:
Thank you everyone, this is what I used though,
function myfunction(x,x2){
var date1 = new Date(x);
var MyDateString;
MyDateString = date1.getFullYear()+ '/' + ('0' + (date1.getMonth()+1)).slice(-2) + '/' + ('0' + date1.getDate()).slice(-2);
x2.value= MyDateString;
}
x, being the datepicker value and x2 being the datepicker object
回答7:
Try this
$(function() {
$("#birth_date").datepicker({
onSelect: function() {
console.log("You Code Here");
}});
});
回答8:
if you are using date picker of jquery there is no need of calender event fire. you can fire the event on textbox "textchanged"
来源:https://stackoverflow.com/questions/27506111/jquery-datepicker-change-event-trigger-and-inputs-default-change-event