admin管理员组文章数量:1417434
I want to submit the value of a textbox when the user presses enter, and finally clear the input. I tried this code:
input.keydown(function(e) {
if (e.keyCode == 13) {
e.preventDefault();
$(this).val('');
...
}
The input field's text clears as it's supposed to, but after clearing, the newline is still entered in the input. This means that the user has to remove this newline after sending a message every time. Is there a way to prevent this newline from appearing, aside from hack-ish methods like setting an interval?
I want to submit the value of a textbox when the user presses enter, and finally clear the input. I tried this code:
input.keydown(function(e) {
if (e.keyCode == 13) {
e.preventDefault();
$(this).val('');
...
}
The input field's text clears as it's supposed to, but after clearing, the newline is still entered in the input. This means that the user has to remove this newline after sending a message every time. Is there a way to prevent this newline from appearing, aside from hack-ish methods like setting an interval?
Share Improve this question edited Apr 23, 2013 at 10:25 George 36.8k9 gold badges69 silver badges109 bronze badges asked Apr 23, 2013 at 10:14 Guido PassageGuido Passage 1,0501 gold badge10 silver badges15 bronze badges3 Answers
Reset to default 5Just return false when enter is pressed:
input.keydown(function(e) {
if (e.keyCode == 13) {
e.preventDefault();
$(this).val('');
return false;
}
}
Of course this means that your end-user won't be able to actually create a new line. In this case I usually have a boolean variable that changes when the shift key is pressed/released. So if shift is down, don't submit, make a new line.
If you're submitting with AJAX you can clear the input after collecting the data for the AJAX payload.
If you're doing a regular page changing submit, you could add an onbeforeunload
callback that clears the input.
Return false
in the keydown
event, this prevents the event from bubbling down so it never actually does anything to the textbox.
input.keydown(function(e) {
if (e.keyCode == 13) {
$(this).val('');
e.preventDefault();
return false;
}
}
本文标签: javascriptclear HTML input after enter and prevent new lineStack Overflow
版权声明:本文标题:javascript - clear HTML input after enter and prevent new line - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745257443a2650186.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论