In Which TextBox is the cursor.?

2020-07-17 16:30发布

I have 4 textboxes and a submit button in my webpage 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..??

3条回答
仙女界的扛把子
2楼-- · 2020-07-17 17:07

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>
查看更多
▲ chillily
3楼-- · 2020-07-17 17:16

You're looking for document.activeElement, which returns the currently focused element.

查看更多
走好不送
4楼-- · 2020-07-17 17:19

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);
});
查看更多
登录 后发表回答