Reputation: 302
I have two textboxes and a button as follows:
My objective is that when the user is typing into textbox ID
it must set a focus on the button.
What I tried:
$(document).on('keypress', '#ID', function () {
$("#Btn").focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" size="10" id="code" name="code">
<input type="text" size="10" id="ID" name="ID">
<input type="button" value="choose" name="Btn" id="Btn">
Every time I type one letter in it switches the focus to the button, which it's doing what I'm telling it to.
But the question I have is how do I let the user type continuously into the textbox while the focus is set on the button? I do not want the button to be focused on page load, only when the user types into the ID
textbox should focus be set on the button.
Is there a way to achieve this?
Upvotes: 1
Views: 66
Reputation: 2854
Or you could target the button with general sibling selector when input[type="text"]
has focus
input[type="text"]:focus ~ input[type="button"] {
background: red
}
<input type="text" size="10" id="code" name="code">
<input type="text" size="10" id="ID" name="ID">
<input type="button" value="choose" name="Btn" id="Btn">
Upvotes: 3
Reputation: 23859
Changing the focus to button will prevent any interaction with the text box. So, an alternative solution will be something like the following:
$(document).on('keypress', '#ID', function() {
$("#Btn").addClass('focused');
});
.focused {
border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" size="10" id="code" name="code">
<input type="text" size="10" id="ID" name="ID">
<input type="button" value="choose" name="Btn" id="Btn">
You can assign a class, which resembles the focus, to the button when there is any keypress on the text box. Of course the CSS can further be tweaked so that your button looks like similar to when its not focused.
So, you need to work on the CSS a bit to give the button a consistent look and feel.
Upvotes: 3