如何使javascript focus()方法在onBlur事件中工作输入文本框? [英] How to make javascript focus() method work in onBlur event for input text box?

查看:126
本文介绍了如何使javascript focus()方法在onBlur事件中工作输入文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我,javascript focus()方法工作正常,如果我使用它与一个按钮和onClick事件,但从onBlur从一个文本框,它不工作。任何人可以指导我这个?

for me javascript focus() method is working fine if i use it with a button and onClick event, but with onBlur from a text box, it is not working.Can anyone guide me on this?

<html>
<head>
<script type="text/javascript">
function displayResult()
{
var inp1=document.getElementById("text1").value;
var inp2=inp1.length;
if(inp2==0)
{
alert("Field 1 cannot be left Empty");
//document.getElementById("text1").value="";
document.getElementById("text1").focus();
}
}
</script>
</head>
<body>
<input type="text" name="text1" id="text1" onBlur="displayResult();"/>
<input type="text" name="yext2" id="text2" />


</body>
</html>


推荐答案

自从您发布问题之后,使用不同的技术问题一个小时。现在在我看来,通过一个输入的事件,你不能把重点放在自己身上。

Since the time you posted the question, I experimented your issue for an hour using different techniques. It now seems to me that through an event on an input, you cannot set focus on itself.

仍然有另一种可能的解决方法。在提交表单时,可以调用 displayResult(),检查 text1 是否为空,如果为空,则取消提交并将重点放在 text1 上。我已经为您重写了代码。

Still, There is another possible workaround. You can call displayResult() when the form is submitted, check if text1 is empty and cancel submit if it is empty and set focus on text1. I have rewritten the code for you.

<html>
<head>
<script type="text/javascript">
function displayResult()
{
var inp1=document.getElementById("text1").value;
var inp2=inp1.length;
if(inp2==0)
{
alert("Field 1 cannot be left Empty");
document.getElementById("text1").focus();
return false;
}
}
</script>
</head>
<body>
<form onsubmit="return displayResult();">
<input type="text" name="text1" id="text1" />
<input type="text" name="yext2" id="text2" />
<input type="submit"  />
</form>

</body>
</html>

希望有帮助...

和平在你身上...

这篇关于如何使javascript focus()方法在onBlur事件中工作输入文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆