Question

I have a page where Ajax updates the feed every once in a while. Under each post there's a textarea for a reply. JQuery/Ajax can post the reply to the database without any problems when the textarea is active. I press the submit button and everything goes well.

However, if I click somewhere else on the page and the textarea becomes inactive, the submit button doesn't work anymore like it should: it submits the form to root and doesn't run the Ajax function.

Can you figure out what's wrong in my code? Thank you for your help!

There are as many forms as there are messages on the pages. The forms look like this:

<form class="reply-form">
<textarea id="reply-11123" name="comment" class="plain-editor"></textarea>
<input type="submit" class="submit" value="Reply" />
<input type="hidden" value="URL HERE" name="url" /> 
</form>

Ajax code (at <head>) looks like this:

<script type="text/javascript">
$(document).ready(function() 
{
    $('.reply-form').on('submit', function (event) {
    event.preventDefault();
    var $form = $(this),
    message_data = $form.find('textarea[name="comment"]').val(),
    url = $form.find('input[name="url"]').val();

    var postData = {};
    var prefix = 'data';
    postData[prefix + '[message]'] = message_data;
    var posting = $.post(url, postData);

    });
}
</script>
Was it helpful?

Solution

If your forms are being added to the page dynamically then you need a different event binding that will attach itself to all current and future forms. The current binding you have is called a direct binding, but what you really need is a delegated binding. A different usage of on() will give you that:

$(document).on('submit', 'form.reply-form', function (event) {
     ... 
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top