jQuery表单提交方法不起作用

时间:2018-10-13 16:45:17

标签: javascript jquery ajax

我试图捕获要通过socket.io发送并用于用户通知目的的成功表单提交中的输入字段的值,但是尽管选择了表单,但似乎这三种不同的触发我的jQuery的尝试均失败了元素。有人可以指出我的选择器语句出了什么问题,什么是实现此表单捕获并与socket.io服务器通信的最佳方法?

JavaScript文件:

$(document).ready(function() {
    var socket = io.connect('http://localhost:3000');

    socket.on('notification', function (data) {
        console.log(data);
    });

    $("#button.blog-comment__form-button").on("click", function(event){
        console.log("Comment Form triggered")
        console.log(event);
        //socket.emit('client-notification', { my: 'successful comment' });
    });

    $("#comment-form").bind('ajax:complete',function(result){
        console.log("Comment successfully submitted");
        console.log(result);
    });

    $("#comment-form").submit(function(event){
        console.log(".submit");
        console.log(event);
    });


});

HTML评论表:

<form action="/app/blog/134jr2n/comment" method="post" name="blogComment" id="comment-form">
    <input type="hidden" name="_csrf" value="dsfhj424u2hfi2nf"/>
    <div className="col-md-9">
        <textarea name="comment" class="blog-comment__form-text-area"></textarea>
    </div>
    <div className="col-md-3">
        <button type="submit" className="blog-comment__form-button">Comment</button>
    </div>
</form>

1 个答案:

答案 0 :(得分:0)

将事件绑定到文档,例如:

$(document).on("submit", "#comment-form", function(e){
    e.preventDefault();
    console.log('It works!');
});