我写了一个小评论板,并且一直使用文本输入而没有提交,但使用返回键提交:
<input type="text" id="comment" placeholder="Comment..." class="formInputWall" />
<!-- hide submit button -->
<input type="submit" value="Submit" class="post" id="10" style="position: absolute; left: -9999px" />
然后我有jquery函数:
$(".post").click(function(){
//attaching the click event to submit button
var element = $(this);
var Id = element.attr("id");
var comment = $("#comment").val();
var dataString = 'comment='+ encodeURIComponent(comment);
if(comment=='')
{
}
else
{
$("#loading").show();
$("#loading").fadeIn(400).html(' Adding Comment.....');
$.ajax({
type: "POST", // form method
url: "/pages/includes/list_wall_post.php",// destination
data: dataString,
cache: false,
success: function(html){
$('#wallWall').append('<div class="msgs_row"><div class="msgs_pic"><a href="/' + user_url + '"><img src="' + live_prof_pic + '"></a></div><div class="msgs_comment"><a href="/' + user_url + '" style="text-decoration:none;"><span class="msgs_name">' + name + '</span></a> ' + comment + '<br /><span class="msgs_time">Just now...</span></div></div>');
$("#loadpost").append(html); // apend the destination files
$("#loading").hide(); //hide the loading div
$("#nc").hide();
$("#comment").val(""); //empty the comment box to avoid multiple submission
$('textarea').autogrow();
}
});
}
return false;
});
这一切都很好,但我想给我们一个文本区域,并使用返回按钮发布表格。
所以我删除了txt输入并替换为:
<textarea id="comment" class="formInputWall"></textarea>
然后添加以下内容:
$(function(){
$('#comment').on('keyup', function(e){
if (e.keyCode == 13) {
// do whatever you want to do, for example submit form
$(".post").trigger('click');
}
});
});
问题是它现在提交了两次,我不明白为什么!有什么想法吗?
并且
答案 0 :(得分:0)
添加return false;
$(function(){
$('#comment').on('keyup', function(e){
if (e.keyCode == 13) {
// do whatever you want to do, for example submit form
$(".post").trigger('click');
return false;
}
});
});
或使用e.preventDefault();
$(function(){
$('#comment').on('keyup', function(e){
if (e.keyCode == 13) {
e.preventDefault();
// do whatever you want to do, for example submit form
$(".post").trigger('click');
}
});
});
答案 1 :(得分:0)
找到了解决问题的不同方法:
$('#comment').bind('keypress', function(e){
var code = e.keyCode ? e.keyCode : e.which;
if(code == 13) // Enter key is pressed
{
// Do stuff here
$(".post").trigger('click');
}
});