将输入元素与表单中的某些按钮相关联?

时间:2010-11-03 15:53:30

标签: javascript html css forms

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 Ready:

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

2 个答案:

答案 0 :(得分: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();
   }
});

答案 1 :(得分:2)

类似的东西:

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

fiddle