In which TextBox is the cursor.?

I have 4 text fields and a submit button on my web page. Suppose the user enters data in 2 fields, and then clicks the submit button. Now I want to know in which text field the cursor was located immediately before pressing the submit button.

Any idea on how to do this in javascript .. ??

+4
source share
3 answers

Your question specifically says javascript , but FWIW is another option in jQuery:

JsFiddle works here

HTML:

<input id="in1" type="text" /><br /> <input id="in2" type="text" /><br /> <input id="in3" type="text" /><br /> <input id="in4" type="text" /><br /> <input type="button" id="mybutt" value="Submit" /> 

JQuery

 var inFocus = false; $('input, textarea').focus(function() { inFocus = $(this).attr('id'); }); $('#mybutt').click(function() { alert('Cursor was last in element id: ' + inFocus); }); 
+2
source

You are looking for document.activeElement that returns the current focused element.

+3
source

you can use document.activeElement

here is a simple example for this.

 <head> <script type="text/javascript"> function GetActive () { if (document.activeElement) { var output = document.getElementById ("output"); output.innerHTML = document.activeElement.tagName; } } </script> </head> <body onclick="GetActive ();"> Click anywhere on the page to get the active element <input id="myInput" value="input field" /> <button>Sample button</button> <div id="output"></div> </body> 
+2
source

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


All Articles