代码之家  ›  专栏  ›  技术社区  ›  Stefan Kendall

将输入元素与窗体中的某些按钮关联?

  •  2
  • Stefan Kendall  · 技术社区  · 14 年前

    http://jsfiddle.net/EGjc9/

    我有几个 <button> <input> 最接近这些按钮的元素。现在,当你击中 ENTER 在任何输入字段上,它都会触发第一个 < 在形式上。我该怎么改?

    国内:

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

    $('button').click( function(){ 
    $(this).siblings().filter('select').val('3');
        return false;
    });
    
    2 回复  |  直到 14 年前
        1
  •  6
  •   Silver Light    14 年前

    您需要使用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();
       }
    });
    
        2
  •  2
  •   Josiah Ruddell    14 年前

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

    fiddle