如何检测type = time的输入是否输入了任何值

时间:2020-02-18 20:41:01

标签: javascript html forms

我有一个javascript脚本,该脚本应该能够在输入type="time"的html表单中输入任何值时进行检测。

但是,每当我输入部分值(例如,键入一个数字,而不是使用AM / PM的完整时间)时,它都不会检测到输入具有值。

在下面的示例中,timeSelector是type="time"的输入。

if (timeSelector.value == "") {
    timeSelector.classList.add("empty");
} else {
    timeSelector.classList.remove("empty");
}

有什么办法可以检测到这种东西吗?

为澄清起见,由于显然我没有清楚地问过我的问题,因此我需要检测一下time输入何时输入了某些内容,即使该输入是无效或不完整的输入也是如此。

2 个答案:

答案 0 :(得分:1)

好了html5输入的问题是,如果输入无效,它们不会在输入中提供文本。因此,当用户从元素中移除焦点时,您可以使用r = / \A # match the beginning of the string Total:\ {3} # match 'Total:' followed by 3 digits ( # begin capture group 1 \d{1,3} # match 1, 2 or 3 digits (?:\ \d{3}) # match a space followed by 3 digits * # perform the previous match zero or more times \.\d{2} # match a period followed by 2 digits ) # end capture group 1 \ \$ # match a space followed by a dollar sign \z # match end of string /x # free-spacing regex definition mode

checkValidity
var checkInput = function() {
  var value = this.value
  var isValid = this.checkValidity()
  if (!this.value.length && isValid) {
    console.log('empty');
  } else if (!this.value.length && !isValid) {
    console.log('invalid time entered')
  } else {
    console.log('valid time entered')
  }
}

var input = document.querySelector("input")

input.addEventListener("input", checkInput)
input.addEventListener("blur", checkInput)

答案 1 :(得分:0)

根据Input Elements上类型为timeHTML Spec)的规范:

value属性(如果已指定且不为空)必须具有一个有效的时间字符串。

如果该元素的值不是有效的时间字符串,则将其设置为空字符串。

这意味着inputchange事件只有在填写了整个时间字段后才会发生。为什么?因为什么都没有真正改变。

您可能认为可以通过使用keydownkeyup事件来规避这一点,但事实并非如此。

该值未更改,因此只有在时间输入框内可以解析为时间的完整字符串之后,该值才可访问。

通过填写以下示例,您可以了解事件如何触发。请注意,在填写所有内容之前缺少value

let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });

on("keydown");
on("keyup");
on("change");
on("input");
<input type="time">


唯一可以避免缺少变化值的方法是设置一个默认值,如下所示:

let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });


on("change");
<input type="time" value="00:00">

但是,使用默认值可能会导致用户提交的时间不是您可能想要的时间。

您可以编写一些验证代码来解决此问题,具体取决于功能的复杂性。

总体如果您需要 这是您需要的东西,并且功能比您认为可以验证自己的地方复杂,则最好自己创建一个时间输入接口(来自其他输入类型),或使用已经完成工作的来源中的库或UI套件。


相关问题