如何在多表单的输入框中使用输入事件javascript

How using enter event javascript in inputbox with multiple form

本文关键字:输入 入事件 javascript 表单      更新时间:2023-09-26

如果像这样,如何在inputbox中使用输入事件javascript

这是我的代码,我使用onclick但不工作,如果使用回车事件如何使用

<form id="msg_1" action="" method="post">
<input type="text" onclick="submit_msg("1")" name="post_msg_1">
</form>
<form id="msg_2" action="" method="post">
<input type="text" onclick="submit_msg('2')" name="post_msg_2">
</form>
<form id="msg_3" action="" method="post">
<input type="text" onclick="submit_msg("3")" name="post_msg_3">
</form>

这是我的javascript

function submit_msg(uid) {
var msg= $("#post_msg_"+uid).val();
var dataString = 'msg='+ msg;
if (msg == '') {
alert("Insertion Failed Some Fields are Blank....!!");
return false;
} else {
$.ajax({
type: "POST",
url: "http://localhost/home/sendcmnt/"+uid,
data: dataString,
cache: true,
success: function(html){
$('#msg_'+uid)[0].reset(); // To reset form fields
}
});
}
return false;
}

如何将inputbox和javascript与enter一起使用?

感谢

这种方法怎么样?

  • 首先输入一些值,然后按输入栏上的回车键
  • 之后,表单将使用Ajax发送表单数据

演示

HTML

<form id="msg_1" action="" method="post">
  <input type="text" data-uid="1" name="post_msg">
</form>
<form id="msg_2" action="" method="post">
  <input type="text" data-uid="2" name="post_msg">
</form>
<form id="msg_3" action="" method="post">
  <input type="text" data-uid="3" name="post_msg">
</form>

和JavaScript

  $('form').on('submit', function(e) {
    var $form = $(this);
    var $post_msg = $form.find('[name="post_msg"]');
    var msg = $post_msg.val();
    var uid = $post_msg.attr('data-uid');
    var dataString = 'msg='+ msg;
    if (msg === '') {
      alert("Insertion Failed Some Fields are Blank....!!");
      return false;
    } else {
      $.ajax({
        type: "POST",
        url: "http://localhost/home/sendcmnt/"+uid,
        data: dataString,
        cache: true,
        success: function(html){
          $form[0].reset(); // To reset form fields
        }
      });
    }
    return false;
  });