PROBLEM IN JQUERY EVENT NOT TRIGGERING

Andrew Watson

Total Post:39

Points:273
Posted by  Andrew Watson
 1011  View(s)
Ratings:
Rate this:

I am trying to trigger a post request when a user clicks the submit button for a comment. Right now clicking the submit button triggers nothing, I even tried to console.log($(this)) I got no output. The first code below is the jQuery event code and ajax code. The block of code below that is the html button. thanks for the help.

 $('#submitComment').on('click', '#content', function() {
        $.ajax({
            url: 'http://localhost:3000/comments',
            type: 'POST',
            data: data = { comment: {
                body: $(this).find('input[name="createComment"]').val(),
                user_id: 1,
                image_set_id: 2}
            }
        }).done(function(response) {
            console.log(response);
        });
    });

the button I am trying to target with jQuery event

<div class="container">
    <div id="content">
      //the code between comments is in a Handelbar template
        <input name="createComment">
        <button type="submit" id="submitComment">Create Comment</button>
       //end of handelbar template
    </div>
</div>

  1. Ashish Pandey

    Post:128

    Points:898
    Re: problem in jQuery event not triggering

    You need to bind the delegated handler to an ancestor(#content) of the target element(submitComment)

    $('#content').on('click', '#submitComment', function () {
        $.ajax({
            url: 'http://localhost:3000/comments',
            type: 'POST',
            data: data = {
                comment: {
                    body:$(this).find('input[name="createComment"]').val(),
                    user_id: 1,
                    image_set_id: 2
                }
            }
        }).done(function (response) {
            console.log(response);
        });
    });

      Modified On Apr-09-2018 12:43:53 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!