gpt4 book ai didi

javascript - 如何按回车键提交数据(jQuery)?

转载 作者:行者123 更新时间:2023-12-02 15:12:28 24 4
gpt4 key购买 nike

我有一个 ajax php 评论系统,工作正常,但它会在按下评论按钮时提交数据。我想提供一些奇特的触摸并删除评论按钮,意味着评论将在回车键上提交。

<form method='post' name='form' action=''>
<input type='text' name='comment' id='comment' placeholder='Write a comment....' />
<input type='button' name='submit' id='submit' value='Comment'/>
</form>

<script type="text/javascript" >
$(function() {
$("#submit").click(function() {
var test = $("#comment").val();
var comment = test;
var id = '<?php echo $id ?>';
if (test == '') {
alert("Please Enter Some Text");
} else {

$.ajax({
type: "POST",
url: "comment.php",
data: {comment : comment,id : id},
cache: false,
success: function(html) {
$(".coments").prepend(html);
$("#comment").val('');
}
});

}
return false;
});
});
</script>

上面的代码带有注释按钮并且工作正常。现在我尝试通过回车键提交评论:

<script type="text/javascript" >
$(function() {
$('#comment').keyup(function(e) {
if(e.keyCode == 13) {
var test = $("#comment").val();
var comment = test;
var id = '<?php echo $id ?>';
if (test == '') {
alert("Please Enter Some Text");
} else {

$.ajax({
type: "POST",
url: "comment.php",
data: {comment : comment,id : id},
cache: false,
success: function(html) {
$(".coments").prepend(html);
$("#comment").val('');
}
});

}
return false;
}
});
});
</script>

此代码在按 Enter 键页面刷新且未提交评论时不起作用。

最佳答案

调整input="button"<input type='submit' name='submit' id='submit' value='Comment'/> .

但是如果您不希望出现提交按钮,您仍然可以使用 css <input type='button' name='submit' id='submit' value='Comment' style="display:none;" /> 隐藏它

然后你就可以使用 jQuery 提交表单了

        $(function() {
$('#comment').keyup(function(e) {
if (e.keyCode == 13) {

var test = $("#comment").val();
var comment = test;
var id = '<?php echo $id ?>';
if (test == '') {
alert("Please Enter Some Text");
} else {

$.ajax({
type: "POST",
url: "comment.php",
data: {comment : comment,id : id},
cache: false,
success: function(html) {
$(".coments").prepend(html);
$("#comment").val('');
}
});

}
}
});

关于javascript - 如何按回车键提交数据(jQuery)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34715214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com