In Which TextBox is the cursor.?

自作多情 提交于 2019-12-21 17:30:05

问题


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..??


回答1:


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);
});



回答2:


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




回答3:


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>


来源:https://stackoverflow.com/questions/18538004/in-which-textbox-is-the-cursor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!