Reputation: 111
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?
Upvotes: 2
Views: 152
Reputation: 5992
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
Upvotes: 3