在克隆的日期选择器上添加onSelect函数

时间:2017-11-01 05:24:05

标签: jquery datepicker

我有日期输入(datepicker)和下面给出的下拉列表

<table>
  <tr id="details1" class="num">
    <td>
      <input type=\"text\" id="datepicker1" class="datepicker">
    </td>
    <td>
      <select id="type1" class="type" onChange="check_error()">
        <option value="">select</option>
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
    </td>
  </tr>
</table>

我通过

在datepicker上添加一个on select函数
<script type="text/javascript">
    $(function() 
    {
      $(".datepicker").datepicker({onSelect: function(date) 
      {
          check_error();
          },dateFormat: 'dd-mm-yy'});                  
    });

</script>

我通过

克隆了上面的日期选择器和下拉列表
<script type="text/javascript">
    function add_input()
    {
      var num = $('.num').length;
      var newNum = num + 1;
      var newElem = $('#details'+num).clone().attr('id', 'details'+ newNum);

      newElem.find("#datepicker"+num).attr('id', 'datepicker' + newNum).attr('class', 'datepicker').datepicker({dateFormat: 'dd-mm-yy'}).attr('value', '');

      newElem.find("#type"+num).attr('id', 'type' + newNum).attr('class', 'type').attr('value', '');

      $('#details'+num).after(newElem);
    }
</script>

but onSelect function on newly cloned datepicker is not working, ie check_error() function is not called on selecting date. How can i add onSelect function on a cloned datepicker also onchange function on cloned dropdown

1 个答案:

答案 0 :(得分:0)

尝试了代码并且运行正常。刚改变了在代码片段中声明函数的方式。

$(function(){
    $(".datepicker").datepicker({onSelect: function(date){
          check_error();
          },dateFormat: 'dd-mm-yy'
    });
    check_error = function(){
    		console.log('check_error');
    }
    
    add_input = function()
    {
      var num = $('.num').length;
      var newNum = num + 1;
      var newElem = $('#details'+num).clone().attr('id', 'details'+ newNum);

      newElem.find("#datepicker"+num).attr('id', 'datepicker' + newNum).attr('class', 'datepicker').datepicker({dateFormat: 'dd-mm-yy'}).attr('value', '');

      newElem.find("#type"+num).attr('id', 'type' + newNum).attr('class', 'type').attr('value', '');

      $('#details'+num).after(newElem);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.3/datepicker.js"></script>
<table>
  <tr id="details1" class="num">
    <td>
      <input type="text" id="datepicker1" class="datepicker">
    </td>
    <td>
      <select id="type1" class="type" onChange="check_error()">
        <option value="">select</option>
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
    </td>
  </tr>
</table>
<button id='clone' onClick='add_input()'>Clone</button>