【问题标题】:submit a comment form with jquery that has multiple id使用具有多个 id 的 jquery 提交评论表单
【发布时间】:2017-11-14 16:56:52
【问题描述】:

我在jquery中有下面的表格

  ' <form class="form comment_form" role="form" id="'+this._id+'" name="comment-form" action="/users/reply" method="post">'+
            '<div class="form-group">'+
            '<input type="hidden" name="post_id" value="'+this._id+'"/> ' +
            '<input class="form-control col-lg-12 red" style="width:100%" type="text" name="user_comment" placeholder="Your comments" />'+
            '</div>'+
            '<div class="form-group">'+
            '</div>'+
            '</form>' +

我正在尝试提交表单,但它有一个特定的 ID。该表单只是一个输入字段,我只想在用户按 Enter 时提交它。类似于脸书。我的问题是我如何让用户通过按下回车按钮来提交特定的表单?

【问题讨论】:

  • 所有表单ID都是唯一的。 (id="'+this._id+')
  • 只需在您的代码中添加一个&lt;input type="submit" value="Submit"&gt;,它将在 Enter 按钮上提交表单
  • 感谢@ManishYadav,但我尝试使用 jquery 提交表单,因此当按下回车按钮时,页面不应该刷新。我正在尝试使用 e.which 语句,但选择了我不熟悉的特定形式。

标签: javascript jquery html node.js forms


【解决方案1】:

id 必须是唯一的。此外,带有提交按钮的表单可用于触发 submit 在按下回车时

'<form class="form comment_form" role="form" id="' + this._id + '" name="comment-form" action="/users/reply" method="post">' +
  '<div class="form-group">' +
  '<input type="hidden" name="post_id" value="input_' + this._id + '"/> ' +
  '<input class="form-control col-lg-12 red" style="width:100%" type="text" name="user_comment" placeholder="Your comments" />' +
  '</div>' +
  '<div class="form-group">' +
  '</div>' +
  '<div><button type="submit">Submit</button></div>'+
  '</form>'

或者如果没有提交按钮,你可以使用javascript/jquery提交表单

$("body").find("#yourFormId").find('input').keypress(function(e) {
  // check for enter/return
  if (e.which == 10 || e.which == 13) {
    $("body > #yourFormId").submit();
  }
});

【讨论】:

  • 感谢您的回复@brk 似乎是一个很好的方法,但我如何找到表单的特定 ID
  • 再次感谢该解决方案,它帮助我找到了正确的方法。我找到了表单的类名并使用 this 关键字查找表单的其他元素
【解决方案2】:

我成功地找到了我的问题的答案。我所做的是我使用 this 关键字来查找表单的其他元素。

var form = $('form.comment_form');
    form.on('submit',function(e){
    e.preventDefault();
    var input = $(this).find('input[type=text]'),
    comment_id = $(this).find('input[name=post_id]');
    })

【讨论】:

    猜你喜欢
    • 2018-04-09
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多