Use the same script for multiple forms

3

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!

    
asked by anonymous 23.05.2018 / 19:49

1 answer

4

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".

    
23.05.2018 / 19:58