admin管理员组文章数量:1391947
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/
本文标签: javascriptFire event on hit enter and changeStack Overflow
版权声明:本文标题:javascript - Fire event on hit enter and change - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744750703a2623158.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论