【问题标题】:check if the value in a datepicker html element is empty and execute jquery function检查 datepicker html 元素中的值是否为空并执行 jquery 函数
【发布时间】:2014-03-13 12:47:56
【问题描述】:

我在表单中使用 jquery datepicker。我正在使用 jquery 检查日期是否为空,并检查所选日期是否为星期日。

我正在使用 Blur 功能,因为我找不到日期选择器的任何事件来检查值是否为空。

使用 Blur 函数,我可以通过在 setinterval 函数中执行 Ajax 来检查日期是否为星期日。

但现在的问题是,如果我选择了日期选择器并且我超过了 setinterval 函数中设置的时间。它不执行检查日期是否为星期日。我该如何解决这个问题? 我知道增加时间间隔可以解决这个问题,但我想要一个可以触发函数来检查该日期是否是星期天的事件或其他东西。

以下是我的代码。

下面html文件中的datepicker元素

<p class="datepair" data-language="javascript">
 <label>Day<em>*</em></label>
 <input type="text" id="date_o" placeholder="Please select date" class="date start" />
</p> 

jquery函数如下:

$(function(){
    $('.datepair input.date').blur(function () {
        setTimeout(function () { 
          if($("#date_o").val() != '' ){
            var date_val = $("#date_o").val();
            $.ajax({
              data: 'date='+date_val,
              url:'common/ajax/date_check.php',
              success:function(data){
                if(data=="sunday"){
                  alert('Sorry You cant book on a Sunday.!!!');
                  $("#date_o").val('');
                }else{

                }
              }
            });
          }else{

          }
        },3000);
    });
  });

和 php 文件来检查日期是否是星期天。在 date_check.php 的 3 秒内工作:

if(date('w', strtotime($_REQUEST['date'])) == 0) {
  echo 'sunday'; 
}

【问题讨论】:

    标签: javascript php jquery html datepicker


    【解决方案1】:

    使用.onSelect() 事件:

    $("#date_o").datepicker({
        onSelect: function(dateText, inst) {
            if($("#date_o").val() != '' ){
                var date_val = $("#date_o").val();
                $.ajax({
                    data: 'date='+date_val,
                    url:'common/ajax/date_check.php',
                    success:function(data){
                        if(data=="sunday"){
                          alert('Sorry You cant book on a Sunday.!!!');
                          $("#date_o").val('');
                        }else{
    
                        }
                    }
                });
            }
        }
    });
    

    您也不需要使用服务器端来检查当天是否是星期天:

    $("#date_o").datepicker({
        onSelect: function(dateText, inst) {
            var d = new Date(dateText);
            if(d.getDay() == 0){
                alert('You cannot choose sunday!');
                $('#date_o').val('');
            }
        }
    });
    

    Here's a working jsFiddle

    【讨论】:

    • 当我使用 onSelect 事件时,我的日期选择器停止工作。它显示了日期选择器,但是当我单击任何日期时,我无法选择任何日期。
    • @Lorenzo 看@我的小提琴链接。比较差异,检查您的控制台;问题不在于我提供的代码。
    • 我猜你在使用不同的日期选择器。
    • 我将我的日期选择器更改为您在小提琴中使用的一个并且它有效。
    猜你喜欢
    • 2016-06-27
    • 2011-10-12
    • 2011-05-05
    • 1970-01-01
    • 2018-05-20
    • 2022-01-04
    • 2016-10-04
    • 2014-10-20
    • 2019-09-02
    相关资源
    最近更新 更多