I have 4 textboxes and a submit button in my web page. Suppose the user enters data in 2 fields and then clicks the submit button. I now want to know in which textbox the cursor was located just before the submit button was clicked.
Any idea on how to do this in Javascript?
I have 4 textboxes and a submit button in my web page. Suppose the user enters data in 2 fields and then clicks the submit button. I now want to know in which textbox the cursor was located just before the submit button was clicked.
Any idea on how to do this in Javascript?
Share Improve this question edited May 28, 2021 at 21:09 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Aug 30, 2013 at 16:57 PradeepPradeep 1,2236 gold badges28 silver badges45 bronze badges 1- document.activeElement try that – Tuxes3 Commented Aug 30, 2013 at 17:28
3 Answers
Reset to default 3You're looking for document.activeElement
, which returns the currently focused element.
Your question does specifically say in javascript, but FWIW here is another option in jQuery:
Working jsFiddle 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);
});
you can use document.activeElement
here is the simple example for the same.
<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>