简体   繁体   中英

Get the active field ID using javascript

I have about 30 input all text, I have a button that I want to get the ID of the focused one when the button press. How can I get that?

Focus is tricky. As soon as some other element (like a button is clicked), the focus my have already moved so you can't see what input field was last active by looking at the focus.

You could attach event handlers for the focus event to each input element and keep track yourself of which one last received the focus and then use that variable when the button is pressed.

Perhaps if you describe the actual problem you're trying to solve, we could offer an even better solution.

You can see an example here of remembering the last active input field: http://jsfiddle.net/jfriend00/XmqPe/ . Click the button and the last active field will be highlighted in red.

var lastInput;
function gotInput() {
    lastInput = this;
}

function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(event, fn);
    } else {
        elem.attachEvent("on" + event, function() {
            fn.call(elem, window.event);
        });
    }
}


var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
    addEvent(inputs[i], 'focus', gotInput);
}

addEvent(document.getElementById('test'), 'click', function() {
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].style.borderColor = '#000';
    }
    if (lastInput) {
        lastInput.style.borderColor = '#F00';
    }
});​

You can try this workaround to get the last input with focus in a button press:

Example using jquery:

<script type="text/javascript">
    $(document).ready(function () {

        var lastId = null;


        $(".inputTest").focus(function () {
            //put the last input id in a "global" variable:
            lastId = $(this).attr("id");
        });

        $("#btnTest").click(function () {

            if (lastId) {
                //if exists, do something:
                alert(lastId);
            }
        });
    });
</script>

Html example:

<body>
     <input type="text" name="test1" id="test1" class="inputTest" />
     <input type="text" name="test2" id="test2" class="inputTest"/>
     <input type="text" name="test3" id="test3" class="inputTest" />
     <input type="text" name="test4" id="test4" class="inputTest" />
     <input type="text" name="test5" id="test5" class="inputTest" />
     <input type="text" name="test6" id="test6" class="inputTest" />

     <input type="button" value="test" id="btnTest" />

</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM