Putting focus on a textbox in onchange event

ε祈祈猫儿з 提交于 2020-01-03 03:16:23

问题


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.com/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.


回答1:


When 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>



回答2:


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.com/ofeva



来源:https://stackoverflow.com/questions/2097840/putting-focus-on-a-textbox-in-onchange-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!