2016-11-30 64 views
0

我有兩個文本框,分別是start_dateend_date將事件監聽器添加到用datepicker啓動的文本框中

我不能addEventListener用datepicker啓動後,我能夠處理文本框上的事件。下面的 是我的js代碼。

document.addEventListener("DOMContentLoaded",function(){ 
        //$("#start_date").datepicker(); 
        $("#end_date").datepicker(); 
        /*$('.d_picker').keydown(function(){ 
         return false; 
        });*/ 
        var startDate = document.getElementById('start_date'); 
        startDate.addEventListener('change',function(){ 
         /*startDateVal = document.getElementById('start_date').value; 
         $("#end_date").datepicker("option","minDate",startDateVal);*/ 
         console.log('Element '+this.name+' clicked'); 
        },true); 

        var endDate = document.getElementById('end_date'); 
        endDate.addEventListener('change',function(){ 
         console.log('Element '+this.name+' clicked'); 
        },true); 
       }); 

我得到下面的輸出中控制檯:

元起始日期點擊

但END_DATE事件絕不會在變化

<html> 
    <head> 
     <title>event listeners in javascript</title> 
     <link type="text/css" rel="stylesheet" href="assets/third_party_libs/jquery/jquery_ui/jquery-ui.css"> 
    </head> 
    <body> 
     <table> 
      <tr> 
       <td>Start Date</td> 
       <td><input type="text" id="start_date" name="start_date" class="d_picker" /></td> 
      </tr> 
      <tr> 
       <td>End Date</td> 
       <td><input type="text" id="end_date" name="end_date" class="d_picker" /></td> 
      </tr> 
     </table> 
     <script src="assets/third_party_libs/jquery/jquery.js"></script> 
     <script src="assets/third_party_libs/jquery/jquery_ui/jquery-ui.js"></script> 
     <script type="text/javascript"> 
      document.addEventListener("DOMContentLoaded",function(){ 
       //$("#start_date").datepicker(); 
       $("#end_date").datepicker(); 
       /*$('.d_picker').keydown(function(){ 
        return false; 
       });*/ 
       var startDate = document.getElementById('start_date'); 
       startDate.addEventListener('change',function(){ 
        /*startDateVal = document.getElementById('start_date').value; 
        $("#end_date").datepicker("option","minDate",startDateVal);*/ 
        console.log('Element '+this.name+'clicked'); 
       },true); 

       var endDate = document.getElementById('end_date'); 
       endDate.addEventListener('change',function(){ 
        console.log('Element '+this.name+'clicked'); 
       },true); 
      }); 
     </script> 
    </body> 
</html> 
+0

嘗試添加e.preventDefault()的結束日期的事件監聽回調裏面? –

+1

可能是因爲沒有'textinput'事件 – adeneo

+0

我懷疑這個庫不會廣播'textinput'事件。 – WillardSolutions

回答

2

如果要使用jQuery,那麼這就是eas IEST解決方案 -

$("#end_date").datepicker({ 
    onSelect: function() { 
     $(this).change(); 
    } 
    }); 

    $('#end_date').on('change', function() { 
    alert('Element ' + this.name + 'clicked'); 
    }); 

https://plnkr.co/edit/jGwZr88ZeHtKPkruAF8u?p=preview