同一页面中的多个datepicker无法正常运行javascript

时间:2014-04-03 05:18:01

标签: jquery html5 jquery-ui datepicker jquery-ui-datepicker

我在表单中使用了添加行删除行功能。我有一个带date picker功能的日期字段。问题是,如果我添加多行,然后单击日期选择器它不能正常工作。有关演示,请参阅此http://jsfiddle.net/KN7Hd/

 $(function() {
    $( "#datepicker" ).datepicker({
      showOn: "button",
      buttonImage: "images/calendar.png",
      buttonImageOnly: true,
      showOtherMonths: true,
      selectOtherMonths: true
    });
  });

如何解决这个问题?

2 个答案:

答案 0 :(得分:10)

看看下面的例子:

http://jsfiddle.net/fMD62/

<input type="text" class="datepick" id="date_1" />
<input type="text" class="datepick" id="date_2" />
<input type="text" class="datepick" id="date_3" />

脚本:

 $('.datepick').each(function(){
    $(this).datepicker();
});

完整代码:

<html>
<head>
 <!-- jQuery JS Includes -->
 <script type="text/javascript" src="jquery/jquery-1.3.2.js"></script>
 <script type="text/javascript" src="jquery/ui/ui.core.js"></script>
 <script type="text/javascript" src="jquery/ui/ui.datepicker.js"></script>

 <!-- jQuery CSS Includes -->
 <link type="text/css" href="jquery/themes/base/ui.core.css" rel="stylesheet" />
 <link type="text/css" href="jquery/themes/base/ui.datepicker.css" rel="stylesheet" />
 <link type="text/css" href="jquery/themes/base/ui.theme.css" rel="stylesheet" />

 <!-- Setup Datepicker -->
 <script type="text/javascript"><!--
  $(function() {
   $('input').filter('.datepicker').datepicker({
    changeMonth: true,
    changeYear: true,
    showOn: 'button',
    buttonImage: 'jquery/images/calendar.gif',
    buttonImageOnly: true
   });
  });
 --></script>
</head>
<body>

 <!-- Each input field needs a unique id, but all need to be datepicker -->
 <p>Date 1: <input id="one" class="datepicker" type="text" readonly="true"></p>
 <p>Date 2: <input id="two" class="datepicker" type="text" readonly="true"></p>
 <p>Date 3: <input id="three" class="datepicker" type="text" readonly="true"></p>

</body>
</html>

答案 1 :(得分:3)

<script type="text/javascript">
        $(document).on('focus', '.datepicker',function(){
            $(this).datepicker({
                todayHighlight:true,
                format:'yyyy-mm-dd',
                autoclose:true
            })
        });
    </script>

<input type="text" class="datepicker" />
<input type="text" class="datepicker" />
<input type="text" class="datepicker" />