2010-11-03 63 views
2

http://jsfiddle.net/EGjc9/将输入元素与表单中的某些按钮关联起来?

我有一个页面上的几个<button>元素,我需要离他们最近的<input>元素关联到这些按钮。现在,当你在任何输入字段上点击ENTER时,它会触发表格中的第一个<button>。我该如何改变这一点?

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已准备就绪:

$('button').click(function(){ 
$(this).siblings().filter('select').val('3'); 
    return false; 
}); 

回答

6

您需要使用KeyPress事件搭上 “Enter” 键按下,然后按您想使用的JavaScript的按钮。

例如:

//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(); 
    } 
}); 
+0

这让我伤心。 – 2010-11-03 17:08:15

+0

(event.keycode || event.which),请参阅:http://stackoverflow.com/questions/302122/jquery-event-keypress-which-key-was-pressed – 2010-11-03 17:57:08

2

是这样的:

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

fiddle

相关问题