Wazdesign
Wazdesign

Reputation: 83

Fire event on hit enter and change

I have one text box when user enter in text box and hit enter it should alert the value, and also if user change the value it should also alert. So there will be two events keypress and change. And I want call this with minimum code. no duplicate codes.

$('#txt').keydown(function (e){
    if(e.keyCode == 13){
        alert('you pressed enter ^_^');
    }
})​

Online Demo

Upvotes: 2

Views: 1244

Answers (4)

Greg
Greg

Reputation: 31378

This is how I would approach this problem.

http://jsfiddle.net/tThq5/3/

Notes: I'm using $.live() (v.1.3) rather than $.on() (v1.7) and also returning false so I don't get more than 1 event fired.

$('#txt').live('keypress change', function(e) {
    if (e.type === 'keypress' && e.keyCode == 13) {
        alert('you pressed enter');
        return false;
    } else if (e.type === 'change') {
        alert('you made a change');
        return false;
    }
});​

Upvotes: 3

KP.
KP.

Reputation: 13730

Try the live approach:

$("#txt").live({
    change: function(e) {
        alert('you changed the value');
    },
    keydown: function(e) {
        if (e.keyCode == 13) {
            alert('you pressed enter ^_^');
        }
    }
});

http://jsfiddle.net/tThq5/1/

Upvotes: 1

Yoshi
Yoshi

Reputation: 54649

You can list multiple events as the first parameter (though you still have to handle each event):

$('#txt').bind('keypress change', function (e){
    if(e.type === 'change' || e.keyCode == 13) {
        alert('you pressed enter ^_^');
    }
})​;​

I'm using bind on purpose, because the OTs fiddle uses jQ 1.5.2

Upvotes: 6

Stefan
Stefan

Reputation: 5662

Something like this?

$('#txt')
    .keydown(function (e) {
        if(e.keyCode == 13){
            alert('you pressed enter ^_^');
        }
    })
    .change(function(e) {
        alert('you changed the text ^_-');
    });

Upvotes: 1

Related Questions