javascript 如何从JS更改输入类型日期的最大值或最小值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16611774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:20:36  来源:igfitidea点击:

How to change max or min value of input type date from JS

javascripthtml

提问by mega6382

I have two input type dates like:

我有两个输入类型日期,例如:

<input type="date" name="first_date">

and other like:

和其他类似:

<input type="date" name="second_date" min="first_date">

now what I want to do is that when first_dateis selected than the minimum range of the second_dateis auto filled by javascript.

现在我想要做的是,当first_date被选择时,是second_date由 javascript 自动填充的最小范围。

Any idea how to do this.

任何想法如何做到这一点。

回答by epascarello

Ajax is the XMLHttpRequest object, I doubt you want to call the server.

Ajax 是 XMLHttpRequest 对象,我怀疑你要调用服务器。

Basic JavaScript using an onchange event to set the attribute.

使用 onchange 事件设置属性的基本 JavaScript。

document.getElementById("firstDateId").onchange = function () {
    var input = document.getElementById("secondDateId");
    input.setAttribute("min", this.value);
}

Code could be better using addEventListener.

使用 addEventListener 可以更好地编写代码。

回答by Y2H

I agree with epascarello's answer, only you can replace setAttribut("min/max")with simply .minor .max.

我同意 epascarello 的回答,只有您可以setAttribut("min/max")简单地替换为.min.max

document.getElementById("firstDateId").onchange = function ()
{
  var input = document.getElementById("secondDateId");
  input.min = this.value;
}

回答by J.T. Blum

You should be able to use JavaScript's .setAttribute('min',date)on the element. Check with the W3Cfor details. There's also jQuery's .attr('min',date)if you want to use a library.

您应该能够.setAttribute('min',date)在元素上使用 JavaScript 。详情请咨询W3C.attr('min',date)如果您想使用库,也可以使用 jQuery 。