Detect enter in input elements of a certain class

前端 未结 3 976
陌清茗
陌清茗 2021-02-19 19:57

I need to detect when someone hits \"enter\" in text inputs with a specific class.

My jQuery is as follows:

$(\'input.large\').keypress(function (e) {
           


        
3条回答
  •  萌比男神i
    2021-02-19 20:10

    You can use live (.on()) events in document with keydown (I think this is better). It'll allow you detect keydown in current and future elements that matches with a selector.

    HTML:

    Personal Name
    
    Email

    JS (jQuery 1.7+):

    Note: .which, .code, .charCode and .keyCode is now deprecated. Use the following new solution:

    jQuery(document).on('keydown', 'input.large', function(ev) {
        if(ev.key === 'Enter') {
            // Will change backgroundColor to blue as example
            this.style.backgroundColor = '#EFF';
    
            // Avoid form submit
            return false;
        }
    });
    

    jsFiddle: http://jsfiddle.net/david_proweb/fjgvhubn/2/

提交回复
热议问题