最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery UI Datepicker altField .change function not working? - Stack Overflow

programmeradmin1浏览0评论

Can anyone tell me why the console.log line isn't getting run when I select a date with the jQuery UI Datepicker?

<script type="text/javascript">
    $(window).ready(function() {
        $(function() {
            $("#datepicker").datepicker({ altField: '#dateIntermediate'});
        });
        $('#dateIntermediate').change(function(){ 
            console.log("dateIntermediate changed");
        });
    });
</script>
<p>Date: <input id="datepicker" type="text"></p>
<input type="hidden" id="dateIntermediate" />

Can anyone tell me why the console.log line isn't getting run when I select a date with the jQuery UI Datepicker?

<script type="text/javascript">
    $(window).ready(function() {
        $(function() {
            $("#datepicker").datepicker({ altField: '#dateIntermediate'});
        });
        $('#dateIntermediate').change(function(){ 
            console.log("dateIntermediate changed");
        });
    });
</script>
<p>Date: <input id="datepicker" type="text"></p>
<input type="hidden" id="dateIntermediate" />
Share Improve this question edited Aug 18, 2021 at 7:39 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 24, 2010 at 12:50 benben 29.8k42 gold badges128 silver badges182 bronze badges 1
  • I think since it is a hidden field, it is not triggered. DOM onchange event is defined only for the following elements: <input type="text">, <select>, <textarea> (from w3schools.). Try changing it to text box for testing. – Marimuthu Madasamy Commented Jul 24, 2010 at 13:09
Add a ment  | 

1 Answer 1

Reset to default 7

The browser just doesn't fire the change event in these cases (setting the value by script), if you want to know when it happens though, you can use the onSelect handler for the datepicker, like this:

$(function() {
  $("#datepicker").datepicker({ 
    altField: '#dateIntermediate',
    onSelect: function() { 
      alert('Current #dateIntermediate value: ' + $("#dateIntermediate").val());
    }
  });
});

You can test it here. Or, alternatively you can trigger the change handler you currently have in the same way:

$(function() {
  $("#datepicker").datepicker({ 
    altField: '#dateIntermediate',
    onSelect: function() { 
      $("#dateIntermediate").change();
    }
  });
  $('#dateIntermediate').change(function(){ 
    console.log("dateIntermediate changed");
  });
});​

You can test that here


As an aside, you don't need the $(window).ready(function() { }); wrapper on there, it's equivalent to $(document).ready(function() { }); which is already handled by your $(function() { }); wrapper. Your current method works because $(anything).ready() all goes to the same place, but there's no need for more than one wrapper, so just remove the outer one :)

发布评论

评论列表(0)

  1. 暂无评论