0

如何if在日期选择器中为特定日期设置条件?
例如,当用户在日期选择器中插入特定日期时,会出现一条消息并报告是否存在事件。

function myFunction() {
  var x, text;
  // Get the value of input field with id="test"
  x = document.getElementById("test").value;
  if (x == "07/21/2019") {
    text = "Birthday event";
  } else {
    text = "No events";
  }
  document.getElementById("demo").innerHTML = text;
}
<p>make if conditional for a specific day in datepicker</p> <input id="test" type="date"> <button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>

4

2 回答 2

0

为此,您需要从日期选择器和您有事件的日期数组中检索选定的日期。然后你必须对它们进行比较。

这是显示日期选择器的 HTML 代码。

Select a day : <input type="date" id="selectedDate">
<button onclick="checkEventDate()"> Check Events</button>

这是 JavaScript 函数

function checkEventDate() {
    //Get the date selected from the Date Picker and convert it to a Date Object
    var selectedDate = new Date(document.getElementById("selectedDate").value);

    //Convert the Date Object to a DateSrting.
    var isSelectedDate = selectedDate.toDateString();

    // Let's assume you have an array of dates which have events 
    var eventDates = ["2019-07-07", "2019-07-08", "2019-07-09"];

    for (var i = 0; i < eventDates.length; i++) {
        //Convert each value in the dates array to a Date Object
        eventDate = new Date(eventDates[i])

        //Convert every Date Object to a DateString type
        iseventDate = eventDate.toDateString();

        //Now compare if the selected date is a event date
        if (iseventDate == isSelectedDate) {
            alert("There is an event on the selected date.");
        }
    }
}
于 2019-07-17T10:19:17.047 回答
0

日期值采用以下格式:

yyyy-mm-dd

<input type="date">

需要注意的一点是,显示的日期格式与实际值不同——显示的日期格式将根据用户浏览器的设置区域设置来选择,而日期值的格式始终为 yyyy-mm-dd

function myFunction() {
  var x, text;
  // Get the value of input field with id="test"
  x = document.getElementById("test").value;
  console.log(x);
  if (x == "2017-07-21") {
    text = "Birthday event";
  } else {
    text = "No events";
  }
  document.getElementById("demo").innerHTML = text;
}
<p>make if conditional for a specific day in datepicker</p>
<input id="test" type="date" value="2017-07-21">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>

另请参阅HTML 中使用的日期和时间格式

于 2019-07-17T08:42:22.693 回答