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
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
Share Improve this question edited Mar 15, 2012 at 14:20 Felix Kling 818k181 gold badges1.1k silver badges1.2k bronze badges asked Mar 15, 2012 at 14:18 WazdesignWazdesign 831 silver badge10 bronze badges 4- 2 And what's your problem? Seems like you are already getting there. – Felix Kling Commented Mar 15, 2012 at 14:20
- @Felix I want for both keypress and change event. Like user change value and click outside it should alert. – Wazdesign Commented Mar 15, 2012 at 14:24
- Then use api.jquery./bind. – Felix Kling Commented Mar 15, 2012 at 14:30
- Or use api.jquery./live – Greg Commented Mar 15, 2012 at 14:36
4 Answers
Reset to default 6You 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
This is how I would approach this problem.
http://jsfiddle/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;
}
});
Something like this?
$('#txt')
.keydown(function (e) {
if(e.keyCode == 13){
alert('you pressed enter ^_^');
}
})
.change(function(e) {
alert('you changed the text ^_-');
});
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/tThq5/1/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744750704a4591576.html
评论列表(0条)