How to make javascript focus () method work in onBlur event to input text field?

for me, the javascript focus () method works fine if I use it with the button and the onClick event, but it does not work with onBlur from the text box. Can anyone direct me to 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> 
+6
source share
3 answers

Since you posted the question, I have been experimenting with your problem for an hour using different methods. It seems to me that through an event at the entrance you cannot concentrate on yourself.

However, there is another possible workaround. You can call displayResult() when submitting the form, check if text1 empty, and cancel sending if it's empty, and set focus to text1 . I rewrote 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> 

Hope this helps ...

Peace to you...

+1
source

You cannot reapply focus to an element when a blur event fires. Use a timer with an interval value of 0 to delay the focus call until the following:

 function displayResult() { var inp1 = document.getElementById("text1").value, inp2 = inp1.length; if(inp2==0) { alert("Field 1 cannot be left Empty"); //document.getElementById("text1").value=""; window.setTimeout(function () { document.getElementById("text1").focus(); }, 0); } } 
+3
source

You need to set a slight delay in focusing the field.

setTimeout (function () {field.focus ()}, 10);

like:

 <html> <head> <script type="text/javascript"> function displayResult(obj) { var inp1=obj.value; var inp2=inp1.length; if(inp2==0) { alert("Field 1 cannot be left Empty"); setTimeout(function(){obj.focus()}, 10); } } </script> </head> <body> <form> <input type="text" name="text1" id="text1" onblur="displayResult(this);"/> <input type="text" name="yext2" id="text2" /> <input type="submit"> </form> </body> </html> 

I advise you not to use onblur when checking input if you are a notification notification as alerts. This is pretty annoying; it causes endless warnings. Confirm event onsubmit form.

+2
source

Source: https://habr.com/ru/post/911722/


All Articles