Chriz74
Chriz74

Reputation: 1480

two forms and two scripts on same page, the first script is invoked regardless of submit

I have a page with two forms, one for submitting some data and return data from DB and the other one which makes an autocomplete search on DB and then should return data from the DB. The two forms work as expected while in different pages, now I tried to put them in one page but if I perform the autocomplete / fulltext search on the second form I get results from the first form. I think the problem is the javascript is catching the data in the first form regardless of what submit button is pressed, the two forms have different action routes. This is the first script:

 jQuery(function ($) {
    $(document).ready(function () {
        var form = $('form');
        form.submit(function (e) {
            e.preventDefault();
            $.ajax({
                url: form.prop('action'),
                type: 'post',
                dataType: 'json',
                data: form.serialize(),
                success: function (data) {
                    var obj = (data);                                        
                    var resultStr = "";

                    //something

                    $("#results").html(resultStr);

                }
            });

        });
    });
});

second one

$(document).ready(function () {
    $('input:text').bind({});
    $('input:hidden').bind({});
    $("#models").autocomplete({
        minLength: 1,
        source: URL

    });
});

so, why is the page returning resultStr and filling the div instead of the data I ask after fulltextsearch using second script? Any idea?

Upvotes: 0

Views: 95

Answers (1)

Victor Levin
Victor Levin

Reputation: 1177

Ok, if you want to attach the same submit event to all your forms and then determine which form is submitted so you can retrieve form's action for example, you need to do the way you did in the first place and then retrieve form object inside the submit block, like so:

Here's jsFiddle example: http://jsfiddle.net/bu9v52fm/

jQuery(function ($) {
    $(document).ready(function () {

        //attach event to all forms
        $('form').submit(function (e) {

           //output $(this) form into a variable and proceed
           //--------------
           var form = $(this);
           //--------------

            e.preventDefault();
            $.ajax({
                url: form.prop('action'),
                type: 'post',
                dataType: 'json',
                data: form.serialize(),
                success: function (data) {
                    var obj = (data);                                        
                    var resultStr = "";

                    //something

                    $("#results").html(resultStr);

                }
            });

        });
    });
});

Upvotes: 1

Related Questions