简体   繁体   中英

Focus matching input field with jquery

I'm trying focus an input field into a div matching with an another input.

I have to skip reference input (first input value). Then, my code is:

$("#btnSearch").on('click',function() {
    input = document.getElementsByTagName('input');
    match = 0;
    for (i=0;i<input.length;i++) {
        if(input[i].value == $("#btnSearch > input").val()) {
            match = 1;
        }else if (match==1) {
            input[i].focus();
            break;
        }
    }
});

But with this code, I focus next input (second input). It doesn't work. Any ideas to improve my code?

You should put your focus if which checks match first like

Instead of

if(input[i].value == $("#btnSearch > input").val()) {
     match = 1;
}else if (match==1) {
    input[i].focus();
    break;
}

You should write

if(match==1) {
        input[i].focus();
        break; 
}else if (input[i].value == $("#btnSearch > input").val()) {
    match = 1;   
}

Exxplanation:

What your code doing is

1) Checks if condition for reference input, sets match to 1, as it is true,

2) Checks if condition for input, sets match to 1, as it is true

3) First if is false but match is true, so sets focus on next input

So we must check for match first, so that we get the focus on actual input

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