Javascript html <input type="text" /> onchange 事件不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6290442/
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-08-23 21:08:05  来源:igfitidea点击:

html <input type="text" /> onchange event not working

javascriptdom-events

提问by Newbie Coder

I am trying to do some experiment. What I want to happen is that everytime the user types in something in the textbox, it will be displayed in a dialog box. I used the onchangeevent property to make it happen but it doesn't work. I still need to press the submit button to make it work. I read about AJAX and I am thinking to learn about this. Do I still need AJAX to make it work or is simple JavaScript enough? Please help.

我正在尝试做一些实验。我想要发生的是,每次用户在文本框中键入内容时,它都会显示在对话框中。我使用onchangeevent 属性来实现它,但它不起作用。我仍然需要按下提交按钮才能使其工作。我阅读了有关 AJAX 的信息,并且正在考虑了解这一点。我是否仍然需要 AJAX 才能使其工作,还是简单的 JavaScript 就足够了?请帮忙。

index.php

index.php

<script type="text/javascript" src="javascript.js"> </script>

<form action="index.php" method="get">
 Integer 1: <input type="text" id="num1" name="num1" onchange="checkInput('num1');" /> <br />
 Integer 2: <input type="text" id="num2" name="num2" onchange="checkInput('num2');" /> <br />
 <input type="submit" value="Compute" />
</form>

javascript.js

javascript.js

function checkInput(textbox) {
 var textInput = document.getElementById(textbox).value;

 alert(textInput); 
}

回答by Ignacio Vazquez-Abrams

onchangeis only triggered when the control is blurred. Try onkeypressinstead.

onchange仅在控件模糊时触发。试试吧onkeypress

回答by rybo111

Use .on('input'...to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.

使用.on('input'...以监视来自jQuery的1.7及以上的每一个变化到输入(粘贴,KEYUP等)。

For static and dynamic inputs:

对于静态和动态输入:

$(document).on('input', '.my-class', function(){
    alert('Input changed');
});

For static inputs only:

仅用于静态输入:

$('.my-class').on('input', function(){
    alert('Input changed');
});

JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/

带有静态/动态示例的 JSFiddle:https://jsfiddle.net/op0zqrgy/7/

回答by Dragonfly

Checking for keystrokes is only a partial solution, because it's possible to change the contents of an input field using mouse clicks. If you right-click into a text field you'll have cut and paste options that you can use to change the value without making a keystroke. Likewise, if autocomplete is enabled then you can left-click into a field and get a dropdown of previously entered text, and you can select from among your choices using a mouse click. Keystroke trapping will not detect either of these types of changes.

检查击键只是一个部分解决方案,因为可以使用鼠标单击来更改输入字段的内容。如果您右键单击文本字段,您将拥有剪切和粘贴选项,您可以使用这些选项更改值而无需敲击键盘。同样,如果启用了自动完成,那么您可以左键单击某个字段并获得先前输入文本的下拉列表,并且您可以使用鼠标单击从您的选择中进行选择。击键捕获不会检测到这些类型的更改中的任何一种。

Sadly, there is no "onchange" event that reports changes immediately, at least as far as I know. But there is a solution that works for all cases: set up a timing event using setInterval().

可悲的是,至少据我所知,没有立即报告更改的“onchange”事件。但是有一个适用于所有情况的解决方案:使用 setInterval() 设置计时事件。

Let's say that your input field has an id and name of "city":

假设您的输入字段的 id 和名称为“city”:

<input type="text" name="city" id="city" />

Have a global variable named "city":

有一个名为“city”的全局变量:

var city = "";

Add this to your page initialization:

将此添加到您的页面初始化中:

setInterval(lookForCityChange, 100);

Then define a lookForCityChange() function:

然后定义一个lookForCityChange()函数:

function lookForCityChange()
{
    var newCity = document.getElementById("city").value;
    if (newCity != city) {
        city = newCity;
        doSomething(city);     // do whatever you need to do
    }
}

In this example, the value of "city" is checked every 100 milliseconds, which you can adjust according to your needs. If you like, use an anonymous function instead of defining lookForCityChange(). Be aware that your code or even the browser might provide an initial value for the input field so you might be notified of a "change" before the user does anything; adjust your code as necessary.

在本例中,“city”的值每 100 毫秒检查一次,您可以根据需要进行调整。如果您愿意,可以使用匿名函数而不是定义 lookForCityChange()。请注意,您的代码甚至浏览器可能会为输入字段提供初始值,因此您可能会在用户执行任何操作之前收到“更改”通知;根据需要调整您的代码。

If the idea of a timing event going off every tenth of a second seems ungainly, you can initiate the timer when the input field receives the focus and terminate it (with clearInterval()) upon a blur. I don't think it's possible to change the value of an input field without its receiving the focus, so turning the timer on and off in this fashion should be safe.

如果每十分之一秒发生一次计时事件的想法看起来很笨拙,您可以在输入字段接收到焦点时启动计时器并在模糊时终止它(使用 clearInterval())。我认为不可能在没有获得焦点的情况下更改输入字段的值,因此以这种方式打开和关闭计时器应该是安全的。

回答by Soufiane ELH

HTML5defines an oninputevent to catch all direct changes. it works for me.

HTML5定义了一个oninput事件来捕获所有直接更改。这个对我有用。

回答by 99 Problems - Syntax ain't one

onchangeonly occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.

onchange仅在用户提交对 input 元素的更改时发生,大多数时候这是元素失去焦点的时候。

if you want your function to fire everytime the element value changes you should use the oninputevent - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc

如果您希望您的函数在每次元素值更改时触发,您应该使用该oninput事件 - 这比键向上/向下事件更好,因为可以使用用户的鼠标(即粘贴或自动填充等)更改该值

Read more about the changeevent here

在此处阅读有关更改事件的更多信息

Read more about the inputevent here

在此处阅读有关输入事件的更多信息

回答by metaforce

use following events instead of "onchange"

使用以下事件而不是“onchange”

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)

回答by Ash Burlaczenko

Firstly, what 'doesn't work'? Do you not see the alert?

首先,什么“不起作用”?你没有看到警报吗?

Also, Your code could be simplified to this

此外,您的代码可以简化为

<input type="text" id="num1" name="num1" onkeydown="checkInput(this);" /> <br />

function checkInput(obj) {
    alert(obj.value); 
}

回答by James Moberg

I encountered issues where Safari wasn't firing "onchange" events on a text input field. I used a jQuery 1.7.2 "change" event and it didn't work either. I ended up using ZURB's textchange event. It works with mouseevents and can fire without leaving the field:
http://www.zurb.com/playground/jquery-text-change-custom-event

我遇到了 Safari 没有在文本输入字段上触发“onchange”事件的问题。我使用了 jQuery 1.7.2 "change" 事件,但它也不起作用。我最终使用了 ZURB 的 textchange 事件。它适用于鼠标事件并且可以在不离开现场的情况下触发:http:
//www.zurb.com/playground/jquery-text-change-custom-event

$('.inputClassToBind').bind('textchange', function (event, previousText) {
    alert($(this).attr('id'));
});

回答by cancerbero

A couple of comments that IMO are important:

IMO 重要的几点意见:

  • input elements not not emitting 'change' event until USER action ENTER or blur await IS the correct behavior.

  • The event you want to use is "input"("oninput"). Here is well demonstrated the different between the two: https://javascript.info/events-change-input

  • The two events signal two different user gestures/moments ("input" event means user is writing or navigating a select list options, but still didn't confirm the change. "change" means user did changed the value (with an enter or blur our)

  • Listening for key events like many here recommended is a bad practice in this case. (like people modifying the default behavior of ENTER on inputs)...

  • jQuery has nothing to do with this. This is all in HTML standard.

  • If you have problems understanding WHY this is the correct behavior, perhaps is helpful, as experiment, use your text editor or browser without a mouse/pad, just a keyboard.

  • 输入元素不会发出“更改”事件,直到用户操作 ENTER 或模糊等待是正确的行为

  • 您要使用的事件是"input"(" oninput")。这里很好地证明了两者之间的不同:https: //javascript.info/events-change-input

  • 这两个事件表示两个不同的用户手势/时刻(“输入”事件表示用户正在编写或导航选择列表选项,但仍未确认更改。“更改”表示用户确实更改了值(输入或模糊我们的)

  • 在这种情况下,像这里推荐的许多关键事件一样监听关键事件是一种不好的做法。(就像人们在输入上修改 ENTER 的默认行为一样)...

  • jQuery 与此无关。这一切都在 HTML 标准中。

  • 如果您在理解为什么这是正确的行为时遇到问题,作为实验,请使用您的文本编辑器或浏览器,而无需鼠标/键盘,只需一个键盘,这可能会有所帮助。

My two cents.

我的两分钱。

回答by Bishnu Paudel

onkeyup worked for me. onkeypress doesn't trigger when pressing back space.

onkeyup 为我工作。按退格键时不会触发 onkeypress。