Use the same script for multiple forms

Posted on

Question :

How do I use only one script for multiple forms?

  <script>
    $(document).ready(function() {
        $("#formPost").submit(function() {
            var dados = $(this).serialize();

            $.ajax({
                type: 'POST',
                url: 'https://jsonplaceholder.typicode.com/posts',
                data: dados,
                success: function(data) {

                }
            });
            return false;
        });
    });
</script>

<form action="" method="POST" id="formPost">
    <input type="text" name="title" />
    <input type="text" name="body" />
    <input type="submit" value="Enviar" />
</form>

        
        
        
    

        
        
        
    

Thank you in advance!

    

Answer :

You can invoke form by tag , instead of invoking id , eg:

$("form").submit(function() {
...

In this case, the same script can be copied (or imported) to multiple pages with different id forms.

If there are more than one form per page, all of them will also be affected, and will have the same “submit function”.

    

Leave a Reply

Your email address will not be published. Required fields are marked *