admin管理员组文章数量:1398294
I am trying to get it so that when a certain value is put into a textbox, the focus will stay on the textbox(and an alert will be shown in production). I am trying to get this to work in Firefox 3.5.7 with no luck.
How can I make it so when a textbox is a certain value at onchange
that it will stay focused/refocus on the textbox?
Live example is at
<body>
Enter your name: <input type="text" name="fname" id="fname" onchange="
if(this.value=='foo'){
this.select();
this.focus();
}
" />
</body>
Also, I don't get any javascript errors or warnings in the Error Console on executing this code.
I am trying to get it so that when a certain value is put into a textbox, the focus will stay on the textbox(and an alert will be shown in production). I am trying to get this to work in Firefox 3.5.7 with no luck.
How can I make it so when a textbox is a certain value at onchange
that it will stay focused/refocus on the textbox?
Live example is at http://jsbin./ipina
<body>
Enter your name: <input type="text" name="fname" id="fname" onchange="
if(this.value=='foo'){
this.select();
this.focus();
}
" />
</body>
Also, I don't get any javascript errors or warnings in the Error Console on executing this code.
Share Improve this question edited Jan 19, 2010 at 23:17 Earlz asked Jan 19, 2010 at 22:54 EarlzEarlz 64k100 gold badges313 silver badges507 bronze badges 2- 1 Are you trying to force focus to stay on that textbox? Wouldn't it have focus if the user is changing it? – brian Commented Jan 19, 2010 at 22:57
- No, the onchange event will not be called(in firefox and IE for textboxes) until the control loses focus – Earlz Commented Jan 19, 2010 at 23:00
2 Answers
Reset to default 2When the onchange
event is fired, the user is focused on the textbox.
Maybe you might want to use the blur
event to re-focus on the textbox if the value is 'foo'.
If you need instantaneous results, you should use onkeyup
.
<body>
Enter your name: <input type="text" name="fname" id="fname" onkeyup="
if(this.value=='foo'){
this.select();
this.focus();
}
" />
</body>
According to Javascript onchange different in IE and FireFox I needed to set the focus after the onchange event occurs, so I had to end up with something like this:
Enter your name: <input type="text" name="fname" id="fname" onblur="
if(this.value=='foo'){
alert('bah');
setTimeout('document.getElementById(\'fname\').focus();document.getElementById(\'fname\').select();',0);
}
" />
And also I had to catch it when the focus was lost, not necessarily when the text was changed, so I had to use onblur instead of onchange.
Live: http://jsbin./ofeva
本文标签: javascriptPutting focus on a textbox in onchange eventStack Overflow
版权声明:本文标题:javascript - Putting focus on a textbox in onchange event - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744128289a2592056.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论