将文本放入数字输入不会触发更改事件? [英] Putting text in a number input doesn't trigger change event?

查看:79
本文介绍了将文本放入数字输入不会触发更改事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例



看来将文本输入< input type =number/> 不会触发更改事件。我想要一个更改事件,以便我可以提醒用户修改他们的输入。我怎样才能得到这个变化事件,并获得当前值,以便我可以验证错误的输入?

我已经在Chrome中进行测试。


$ b

  $('input')。 );  

 < script src =https:// ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>输入我中的字母并按下tab:< input type =number/>  


解决方案

pickypg 指出,如果用户在<输入类型中输入了 abcd , ='number'> 元素,你不能通过 $(this).val()获得值'abcd'。 (注意:我只在Chrome中进行过测试。)然而,您可以通过调用<$ c来确定HTML5输入有效性约束是否满足(有效) $ c> myDOMelement.checkValidity(),或查看 myDOMelement.validity 对象的各个属性。这至少可以让您区分空白字段(有效)和包含 abcd (无效)的空白字段。查看此处了解关于HTML5有效性的更多信息。



至少在Chrome中,令人困惑的是,如果< input type ='number'> 元素最初是空白的,那么你输入' abcd ','change'事件是 不是 被触发在模糊。同样,如果从字段中删除 abcd ,则该字段将变为空白。

解决方法是测试模糊HTML5有效性的变化。这里有一个 jsFiddle 来说明这项技术。请注意,您仍然无法判断用户是否已将 abcd 更改为 efgh ,因为这些内容都无效。


example

It appears that entering text into <input type="number"/> does not trigger a change event. I would like a change event so that I can warn the user to fix their input. How can I get a change event for this, and get the current value so that I can verify the bad input?

I've been testing in Chrome.

$('input').on('change', function() {
    alert('change');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
put letters in me and press tab: <input type="number"/>

解决方案

As pickypg has noted, if a user types 'abcd' into an <input type='number'> element, you cannot get the value 'abcd' via $(this).val(). (Caveat: I've only tested in Chrome.)

However, you can determine whether the HTML5 input validity constraints are satisfied (valid) or not by calling myDOMelement.checkValidity(), or looking at the individual properties of the myDOMelement.validity object. This at least lets you distinguish between a blank field (valid) and one containing 'abcd' (not valid). Check here for more on HTML5 validity.

What is rather confusing, at least in Chrome, is that if an <input type='number'> element is initially blank and then you type in 'abcd', the 'change' event is not fired on blur. Likewise when you delete 'abcd' from the field so the field becomes blank.

A workaround is testing for changes in the HTML5 validity on blur. Here's a jsFiddle to illustrate the technique. Note that you still cannot tell if the user has changed 'abcd' to 'efgh', since those are both not valid.

这篇关于将文本放入数字输入不会触发更改事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆