Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable button on sumbit and re-enable after submit

Tags:

html

jquery

ajax

I have a script below which submits data to the server via ajax and works perfectly. What I want to achieve is to disable the button on submission and re-enable it after submission.

$(document).ready(function(){
    $('.comment').on('submit',function(event){
        event.preventDefault();
        data = $(this).serialize();
        $.ajax({
        type: "POST",
        url: "user_comment.php",
        data: data
        }).success(function(msg) {
   $('#new_entry').html(msg);

            $('.textbox').val("");

        });
    });
});

HTML

<form name="form1" method="post" action="" class="comment">
  <p>
    <label for="comment"></label>
    <textarea name="comment" id="comment"></textarea>
  </p>
  <p>
    <input type="submit" name="button" id="button" value="Submit Comment">
  </p>
</form>
like image 286
i_user Avatar asked Nov 09 '22 10:11

i_user


2 Answers

You can use prop() like

$(document).ready(function() {
    $('.comment').on('submit', function(event) {
        $('#button').prop('disabled', true);
        event.preventDefault();
        data = $(this).serialize();
        $.ajax({
            type: "POST",
            url: "user_comment.php",
            data: data
        }).success(function(msg) {
            $('#button').prop('disabled', false);
            $('#new_entry').html(msg);
            $('.textbox').val("");
        });
    });
});
like image 118
AmmarCSE Avatar answered Nov 15 '22 04:11

AmmarCSE


Try below code. user Ajax beforeSend event for that

$(document).ready(function () {
    $('.comment').on('submit', function (event) {
        event.preventDefault();
        data = $(this).serialize();
        $.ajax({
            type: "POST",
            url: "user_comment.php",
            data: data
            beforeSend: function () {
                $('#button').attr('disabled', true);
            },
            success: function () {
                $('#button').attr('disabled', false);
                $('#new_entry').html(msg);
                $('.textbox').val("");
            });
        });
    });
like image 39
SVIPL Coder Avatar answered Nov 15 '22 05:11

SVIPL Coder