Saddam Meshaal Saddam Meshaal - 1 year ago 120
HTML Question

How to focus Button in java-script

Simply I have this HTML document

<input type="text" id="my_txt" onkeypress="move_focus(event)"/>
<input type="button" id="my_btn" />
<script >
function move_focus(e)
if (e.keyCode==13) $("#my_btn").focus();

What I want is:
on key press event of input-text
, if the pressed key is
key move the focus to

I did it like above BUT that doesn't work and no any action is done when Enter key pressed.

I found more than one post in this network about this topic but most answers are complex and some me away of what I need.

Help Please!.. Thanks in advance.

Answer Source

The important part for this is use of bind. Bind creates a new function that will have this (this) set to the first parameter passed to bind(). So when we write $('#my_txt').bind("enterKey"), it actually maps #my_txt and event enterKey in same context that the function will execute in. So every time we press a key inside input element with id #mytxt, when we release the key it will check if the key pressed is Enter Key or not which is provided by the line $('#my_txt').keyup(e) which takes the event object as parameter. Here the event will be keypress event.

move_focus = function move_focus(e) {
     //disable to prevent multiple enter
     $(this).attr("disabled", "disabled")
     if(e.keyCode == 13)        //checks if the event object is a Enter Key or not
      $(this).trigger("enterKey");   //explicitly triggers enterkey event with whom #my_txt is bound to
<script src=""></script>
<input type="text" id="my_txt" onkeypress="move_focus(event)"/>
<input type="button" id="my_btn" value="button" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download