jquery - 禁用移动 jquery 中的过去日期

标签 jquery jquery-mobile jquery-ui-datepicker

我在移动 jquery 中创建了一个 DatePicker,我想禁用昨天之前的过去日期。我只想在 DatePicker 对话框中保留 2 个可用选项,即“今天”和“昨天”。下面是我的代码.. 谢谢

 

<!DOCTYPE html>

<html>
<head>
    <title></title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="./cs/jquery.mobile-1.4.5.min.css" />
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
    <script type="text/javascript" src="js/jquery.mobile-1.4.5.min.js"></script> 
    <script src="cordova.js"></script> 
</head>
<body>
    <div id="daily" data-role="page" class="ui-page slidehelp" data-theme="a">
         
        <div role="main" class="ui-content" data-theme="b">
            <form> 
                <input name="date" type="date" placeholder="Date" id="datepicker"  minDate: 0 > 
          </form>
        </div>
    </div>
       <script>
$(document).ready(function () {
    $('input[type="date"], input[type="datetime"], input[type="datetime-local"], input[type="month"], input[type="time"], input[type="week"]').each(function () {
        var el = this, type = $(el).attr('type');
        if ($(el).val() == '') $(el).attr('type', 'text');
        $(el).focus(function () {
            $(el).attr('type', type);
            el.click();
        });
        $(el).blur(function () {
            if ($(el).val() == '') $(el).attr('type', 'text');
        });
    });
});

    </script>
</body>
</html>

最佳答案

基本上,您可以使用 beforeShowDay 函数,该函数会针对 datepicker 上显示的每个日期调用。这已经是一个很好的答案,其中包含更多详细信息以及如何使用它:JQuery DatePicker and beforeShowDay

var today = new Date(Date.now()), yesterday = new Date(today - 24 * 60 * 60 * 1000);

function sameDate(a, b){
  return a.getDate() == b.getDate() && a.getMonth() == b.getMonth() && a.getFullYear() == b.getFullYear();
}

$(document).on("pagecreate", "#daily", function() {
    $("#datepicker").datepicker({
      beforeShowDay: function() {
          return [sameDate(date, today) || sameDate(date, yesterday), "",""];
      }
    });
});

顺便说一句,如果您只需要启用两个日期,为什么不使用带有两个单选按钮的漂亮 fieldset 呢?

var today = new Date(Date.now());
var yesterday = new Date(today - 24 * 60 * 60 * 1000);

function formatDate(date) {
  var dd = date.getDate();
  var mm = date.getMonth() + 1;
  var yyyy = date.getFullYear();
  return yyyy + "-" + mm + "-" + dd;
}

$(document).on("pagecreate", "#page-1", function() {
  $("#radio-choice-date-today").prop("value", formatDate(today));
  $("#radio-choice-date-yesterday").prop("value", formatDate(yesterday));
  $("#date-choiche").html($("#radio-choice-date-today").val());
  $("input[name*=radio-choice-date]").click(function() {
    $("input[name*=radio-choice-date]:checked").each(function() {
      $("#date-choiche").html($(this).val());
    });
  });
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>

<body>
  <div data-role="page" id="page-1">
    <div role="main" class="ui-content">
      <form>
        <fieldset data-role="controlgroup" data-type="horizontal">
          <legend>Choose date:</legend>
          <input name="radio-choice-date" id="radio-choice-date-yesterday" value="off" type="radio">
          <label for="radio-choice-date-yesterday">Yesterday</label>
          <input name="radio-choice-date" id="radio-choice-date-today" value="on" checked="checked" type="radio">
          <label for="radio-choice-date-today">Today</label>
        </fieldset>
      </form>
        <p>Selected date:<span id="date-choiche"></span></p>
    </div>
  </div>
</body>

</html>

除此之外,这里是由 Salman Arshad 为 jQuery Mobile 设计的 datepicker 的完整示例,来源:jQuery UI Datepicker for jQuery Mobile

var today = new Date(Date.now());
var yesterday = new Date(today - 24 * 60 * 60 * 1000);

function sameDate(a, b){
  return a.getDate() == b.getDate() && a.getMonth() == b.getMonth() && a.getFullYear() == b.getFullYear();
}

function enableDate(date) {
  var enable = sameDate(date, today) || sameDate(date, yesterday);
  return [enable, "",""];
}

$(document).on("pagecreate", "#daily", function() {
    $("#datepicker").datepicker({
      beforeShowDay: enableDate
    });
});


/*
 * jQuery Mobile: jQuery UI Datepicker Monkey Patch
 * http://salman-w.blogspot.com/2014/03/jquery-ui-datepicker-for-jquery-mobile.html
 */
(function() {
  // use a jQuery Mobile icon on trigger button
  $.datepicker._triggerClass += " ui-btn ui-btn-right ui-icon-carat-d ui-btn-icon-notext ui-corner-all";
  // replace jQuery UI CSS classes with jQuery Mobile CSS classes in the generated HTML
  $.datepicker._generateHTML_old = $.datepicker._generateHTML;
  $.datepicker._generateHTML = function(inst) {
    return $("<div></div>").html(this._generateHTML_old(inst))
      .find(".ui-datepicker-header").removeClass("ui-widget-header ui-helper-clearfix").addClass("ui-bar-inherit").end()
      .find(".ui-datepicker-prev").addClass("ui-btn ui-btn-left ui-icon-carat-l ui-btn-icon-notext").end()
      .find(".ui-datepicker-next").addClass("ui-btn ui-btn-right ui-icon-carat-r ui-btn-icon-notext").end()
      .find(".ui-icon.ui-icon-circle-triangle-e, .ui-icon.ui-icon-circle-triangle-w").replaceWith(function() {
        return this.childNodes;
      }).end()
      .find("span.ui-state-default").removeClass("ui-state-default").addClass("ui-btn").end()
      .find("a.ui-state-default.ui-state-active").removeClass("ui-state-default ui-state-highlight ui-priority-secondary ui-state-active").addClass("ui-btn ui-btn-active").end()
      .find("a.ui-state-default").removeClass("ui-state-default ui-state-highlight ui-priority-secondary").addClass("ui-btn").end()
      .find(".ui-datepicker-buttonpane").removeClass("ui-widget-content").end()
      .find(".ui-datepicker-current").removeClass("ui-state-default ui-priority-secondary").addClass("ui-btn ui-btn-inline ui-mini").end()
      .find(".ui-datepicker-close").removeClass("ui-state-default ui-priority-primary").addClass("ui-btn ui-btn-inline ui-mini").end()
      .html();
  };
  // replace jQuery UI CSS classes with jQuery Mobile CSS classes on the datepicker div, unbind mouseover and mouseout events on the datepicker div
  $.datepicker._newInst_old = $.datepicker._newInst;
  $.datepicker._newInst = function(target, inline) {
    var inst = this._newInst_old(target, inline);
    if (inst.dpDiv.hasClass("ui-widget")) {
      inst.dpDiv.removeClass("ui-widget ui-widget-content ui-helper-clearfix").addClass(inline ? "ui-content" : "ui-content ui-overlay-shadow ui-body-a").unbind("mouseover mouseout");
    }
    return inst;
  };
})();
/*
 * jQuery Mobile: jQuery UI Datepicker Monkey Patch
 * http://salman-w.blogspot.com/2014/03/jquery-ui-datepicker-for-jquery-mobile.html
 */

.ui-datepicker {
  display: none;
}


/* set height and left/right margin to accomodate prev/next icons */

.ui-datepicker-header {
  position: relative;
  padding: 0.3125em 2.0625em;
  line-height: 1.75em;
  text-align: center;
}

.ui-datepicker-header .ui-btn {
  margin: -1px 0 0 0;
}


/* fixed width layout for calendar; cells are fixed width */

.ui-datepicker-calendar {
  border-collapse: collapse;
  line-height: 2;
}

.ui-datepicker-calendar .ui-btn {
  margin: 0;
  padding: 0;
  width: 2em;
  line-height: inherit;
}

.ui-datepicker-today .ui-btn {
  text-decoration: underline !important;
}

.ui-datepicker-days-cell-over .ui-btn {
  border-color: inherit !important;
}

.ui-datepicker-buttonpane .ui-btn {
  float: left;
  margin: 0.5em 0 0;
  padding: 0.5em 1em;
}

.ui-datepicker-buttonpane .ui-btn:last-child {
  float: right;
}


/* class that can be added to datepicker <input> element's wrapper; makes room for trigger button */

.dp-input-button-wrap {
  position: relative;
  padding-right: 2.5em;
}

.dp-input-button-wrap .ui-btn {
  top: 0.1875em;
  margin: 0;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
</head>

<body>
  <div id="daily" data-role="page" class="ui-page" data-theme="a">
    <div role="main" class="ui-content" data-theme="b">
      <form>
        <input name="date" placeholder="Date" id="datepicker">
      </form>
    </div>
  </div>
</body>

</html>

编辑:

从您的代码来看,您似乎需要 native 方法,即 HTML5 input type="date"。在这种情况下,解决方案就更简单了:

var today = new Date(Date.now());
var yesterday = new Date(today - 24 * 60 * 60 * 1000);

function formatDate(date) {
  var dd = date.getDate();
  var mm = date.getMonth()+1;
  var yyyy = date.getFullYear();
  return yyyy + "-" + mm + "-" + dd;
}

$(document).ready(function() {
  $("#datepicker").prop("min", formatDate(yesterday));
  $("#datepicker").prop("max", formatDate(today));
  $('input[type="date"], input[type="datetime"], input[type="datetime-local"], input[type="month"], input[type="time"], input[type="week"]').each(function() {
    var el = this,
      type = $(el).attr('type');
    if ($(el).val() === '') $(el).attr('type', 'text');
    $(el).focus(function() {
      $(el).attr('type', type);
      el.click();
    });
    $(el).blur(function() {
      if ($(el).val() === '') $(el).attr('type', 'text');
    });
  });
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
</head>
<body>
  <div id="daily" data-role="page" class="ui-page slidehelp" data-theme="a">
    <div role="main" class="ui-content" data-theme="b">
      <form>
        <input name="date" type="date" placeholder="Date" id="datepicker">
      </form>
    </div>
  </div>
</body>
</html>

...但是当前的浏览器实现并不总是完美的。您可以引用:Can I use... Date and time input types兼容性和问题。

关于jquery - 禁用移动 jquery 中的过去日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41394932/

相关文章:

javascript - 未捕获错误 : Syntax error, 无法识别的表达式:# Something

c# - 控件在 Chrome 中不会灰显,但在 IE 中会灰显

jquery - 将 mouseenter/mouseleave 合并为一个函数

html - 有什么办法可以防止虚拟智能手机键盘隐藏输入?

javascript - 如何在 jQuery Datepicker ui 中阻止多个日期范围

javascript - 如何在 jQuery UI Datepicker 中禁用下一个周末?

jquery - 使用开始标签与自结束标签创建空元素

jquery-mobile - Spring Roo、jQuery、jQuery 移动

javascript - 如何拒绝输入字段中的相同日期?

javascript - 使用 JQuery Mobile ui-datepicker 保存日期/事件