[英]How can I run a javascript function when input changes
When a user creates a new account on my website I want to check if the name already exists.当用户在我的网站上创建新帐户时,我想检查该名称是否已存在。 I want this check to run when they leave the username input box and go to enter a password.我希望在他们离开用户名输入框并输入密码时运行此检查。
I tried :我试过:
<input type="text" onkeyup="check_user(this.value)"/>
在文本字段的change
事件上调用函数:
<input name="username" onChange="check_user(this.value);" type="text"/>
Because you used onkeyup
in your code example, it sounds like you are looking to call a function on every keystroke.因为您在代码示例中使用了onkeyup
,所以听起来您希望在每次击键时调用一个函数。 If that is the case, then instead of onchange
- which fires when the input
loses focus - you should use oninput
which will fire anytime there is a change inside of input.如果是这种情况,那么代替onchange
- 当input
失去焦点时触发 - 您应该使用oninput
,它会在输入内部发生变化时触发。
You need to use the "onblur" event.您需要使用“onblur”事件。 It fires when a control loses its focus, which seems to be exactly what you need.它在控件失去焦点时触发,这似乎正是您所需要的。
I think you are looking for check the duplication of user.我想你正在寻找检查用户的重复。 you have to write server side code for that.您必须为此编写服务器端代码。
If you want to fire when something specific is type into the window:如果您想在窗口中输入特定内容时触发:
phr = 'lol'
ltr = phr.split('')
text = ''
document.addEventListener('keyup',function(k){
if (ltr.includes(k.key)) {
text += k.key
if (text == phr) {
console.log('Typed!')
text = ''
}
} else {
text = ''
}})
As a function your can use it like:作为一个函数,你可以像这样使用它:
function wtt(phrase,clb) {
phr = phrase
ltr = phr.split('')
text = ''
document.addEventListener('keyup',function(k){
if (ltr.includes(k.key)) {
text += k.key
if (text == phr) {
clb()
text = ''
}
} else {
text = ''
}})
}
wtt('my phrase', function () {
console.log('dostuff')
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.