jQuery - Form still submits with return false

http://jsfiddle.net/QsTfc/

For some odd reason the form keeps submitting even though I am returning false. I have tried:

$("#submitEdit").submit(function() {
    return false;
});

$("#submitEdit").submit(function() {
    event.preventDefault();
});

And this is what I currently have:

<script>

$('a').click(function() {
    var parentId = $(this).closest('tr').attr('id');
    var child = $("#" + parentId).children().eq(1);
    var childText = $(child).text();
    $(child).html('<form action="<?php echo URL; ?>user/changeSettings/' + parentId + '" method="POST" id="submitEdit"><input type="text" name="' + parentId + '" value="' + childText + '" /></form>');
    console.log(childText);
});

$("#submitEdit").on("submit", function() {
    var url = $(this).attr('action');
    var data = $(this).serialize();
    alert(data);
    $.post(url, data, function(returned) {
        $(parentId + "Field").html(returned);
        return false;
    });
    return false;
});

</script>

Answers:

Answer

According to your jsfiddle demo your form is added dinamically. So, you have to use delegation:

$(document).on("submit", "#submitEdit", function() {
    var url = $(this).attr('action');
    var data = $(this).serialize();
    alert(data);
    $.post(url, data, function(returned) {
        $(parentId + "Field").html(returned);
        return false;
    });
    return false;
});

JSFIDDLE

Answer

you need to put your event parameter in your call back function

$("#submitEdit).submit(function(event) {
    event.preventDefault();
});

and try this:

$(document).on("submit", "#submitEdit", function(event) {
    event.preventDefault();
    var url = $(this).attr('action');
    var data = $(this).serialize();
    alert(data);
    $.post(url, data, function(returned) {
        $(parentId + "Field").html(returned);
        return false;
    });
});

when to use return false and when to use event.preventDefault(). you can take a look for this question: When should I use return false in jquery function?

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.