0

I am new in Ajax/ jquery. I have multiple forms in page that can be submitted without page refresh. After every click on submit button corresponding submit button gets disabled.
So far I found script that disables button by founding submit button ID. But in that case I need to repeat that script as many times, as many forms I have in my page and give each submit button uncial ID. How can I improve button disable code, and not repeate #saveButton1, #saveButton2, #saveButton3 ....... all the time?

<script>
$(function () {
$('form').on('submit', function (e) {
    $.ajax({
        type: 'post',
        url: 'post.php',
        data: $(this).serialize(),
        success: function (returnedData ) {
         $( '#message' ).load( 'div.php');

        }
    });
    e.preventDefault();
});
});
</script>




</head>

<body>

<script>
    $(document).ready(function () {
        $('#saveButton1').click(function () {
            $(this).prop("disabled", true);
              $(this).closest('form').trigger('submit');
                   });
    });
</script>

<script>
    $(document).ready(function () {
        $('#saveButton2').click(function () {
            $(this).prop("disabled", true);
             $(this).closest('form').trigger('submit');
                   });
    });
</script>


<form id="form1"  action="" method="post">
Firstname: <input type="text" name="name" /><br><br>
Lastname: <input type="text" name="lastname" /><br><br>

<input id="saveButton1" type="submit" >
</form>



<form id="form2"  action="" method="post">
Firstname: <input type="text" name="name" /><br><br>
Lastname: <input type="text" name="lastname" /><br><br>

<input id="saveButton2" type="submit" >

</form>

<div id='message'></div>




</body>

3 Answers 3

2

You just need one DOM ready handler as well as using $('input[type=submit]') instead of target each input element by id

$(document).ready(function () {
    $('input[type=submit]').click(function () {
        $(this).prop("disabled", true);
        $(this).closest('form').trigger('submit');
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of

$('#saveButton2').click

you could use

$('input[type=submit]').click

Comments

1

You have two options

If you want to disable all submit buttons you can use

$(document).on('click', 'input[type=submit]', function(e) {

$(this).prop("disabled", true); // $(this) selects the clicked button and applies the function you implement on it

});

or particular submit buttons give them a seperate class name like sbmtbtn and disable like this

$(document).on('click', 'input[class=sbmtbtn]', function(e) {

$(this).prop("disabled", true);

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.