html <input type=“text” /> onchange event no

2020-01-27 01:50发布

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 onchange event 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.

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

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

 alert(textInput); 
}

12条回答
放荡不羁爱自由
2楼-- · 2020-01-27 02:25

try onpropertychange. it only works for IE.

查看更多
叛逆
3楼-- · 2020-01-27 02:27

HTML5 defines an oninput event to catch all direct changes. it works for me.

查看更多
forever°为你锁心
4楼-- · 2020-01-27 02:27

use following events instead of "onchange"

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
查看更多
Rolldiameter
5楼-- · 2020-01-27 02:29

A couple of comments that IMO are important:

  • 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.

My two cents.

查看更多
该账号已被封号
6楼-- · 2020-01-27 02:30

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); 
}
查看更多
你好瞎i
7楼-- · 2020-01-27 02:31

It is better to use onchange(event) with <select>. With <input> you can use below event:

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
查看更多
登录 后发表回答