3

http://jsfiddle.net/EGjc9/

I have several <button> elements on a page, and I need to associate the <input> elements nearest them to those buttons. Right now, when you hit ENTER on any input field, it fires the first <button> in the form. How do I change this?

DOM:

<form action="irrelevant">
<div>
<select><option>1</option><option>2</option><option>3</option></select>
    <input type='text'/>
    <button>Hello</button>
</div>
<div>
    <select><option>1</option><option>2</option><option>3</option></select>
    <input type='text'/>
    <button>Hello</button>
</div>
<div>
    <select><option>1</option><option>2</option><option>3</option></select>
    <input type='text'/>
    <button>Hello</button>
</div>
<div>
    <select><option>1</option><option>2</option><option>3</option></select>
    <input type='text'/>
    <button>Hello</button>
</div>
</form>

DOM Ready:

$('button').click( function(){ 
$(this).siblings().filter('select').val('3');
    return false;
});
Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406

2 Answers2

6

You need to use KeyPress event to catch "Enter" key pressed and then push the button you want using javascript.

For example:

//some key is pressed
$('input').keypress( function(event){ 
   //is this "Enter"?
   if (event.keyCode == '13') {
     //finding the button inside the same <div> and clicking on it
     $(this).parent().find('button').click();
     //we don't need a default action
     event.preventDefault();
   }
});
Silver Light
  • 44,202
  • 36
  • 123
  • 164
2

something like this:

$('input').bind('keypress', function(e){
     if(e.which == 13) { //Enter keycode
       $(this).next().click()
     }
     return false;
});

fiddle

Josiah Ruddell
  • 29,697
  • 8
  • 65
  • 67