user2157361
user2157361

Reputation: 21

Submitting from an ajax loaded form

H_i

Have anybody ideas for submitting ajax loaded form: www.example.com/form.php is

<form>
    <fieldset>
        <legend>Your name?</legend>
        <input type="name" id="name" />
        <button type="submit">OK!</button>
    </fieldset>
</form>

and www.example.com/index.php is

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Myform</title>
        <script type="text/javascript" src="jquery.js"></script>
    </head>
    <body>
        <div id="formDiv"></div>
        <button id="open">Open</button>
        <button id="close">Close</button>
        <script type="text/javascript">
            (function($) {
                $(document).ready(function() {
                    $('#open').click(function() {
                        $('#formDiv').load('www.example.com/form.php');
                    });
                    $('#close').click(function() {
                        $('#formDiv').empty();
                    });
                    $('#formDiv form').submit(function() {
                        alert("Hello, "+($('#formDiv form #name').val())+"!");
                        return false;
                    });
                });
            })(jQuery);
        </script>
    </body>
</html>

I want that alerts an "Hello, myname" instead of a submit.

Thank you

Upvotes: 1

Views: 5763

Answers (4)

Loken Makwana
Loken Makwana

Reputation: 3848

your forms submit event will not work because when it's executed, the form may not be loaded Instead you should write the event on callback of load event like below

$('#formDiv').load('www.example.com/form.php',{},function() {
    $('#formDiv form').submit(function(event) {
        event.preventDefault();
        alert("Hello, "+($('#formDiv form #name').val())+"!");
    });
});

also in this case return false; will not work you need to use event.preventDefault()

Upvotes: 3

Anthony Grist
Anthony Grist

Reputation: 38345

Use event delegation to set up an event handler for the dynamically loaded form:

$('#formDiv').on('submit', 'form', function(event) {
    alert("Hello, "+($('#name').val())+"!");
    return false;
});

Upvotes: 5

Red
Red

Reputation: 6378

Try

 $('#formDiv form').live('submit',function() {
           alert("Hello, "+($('#formDiv form #name').val())+"!");
           return false;
    });

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You need to use event delegation using jQuery.on

$('#formDiv').on('submit', 'form', function() {
    alert("Hello, "+($('#formDiv form #name').val())+"!");
    return false;
});

Upvotes: 2

Related Questions