Toni Michel Caubet
Toni Michel Caubet

Reputation: 20163

Disable button after post using JS/Jquery

I would like to have a function to add an onclick event to my form buttons to get them disabled in order to avoid double posting.

<form>
   <button onclick="disable(this)" type="submit">post</button>
</form>
<script> function disable(button){ $(button). ??? }</script>

Ani idea or tip? thanks!

Upvotes: 1

Views: 3445

Answers (4)

Scoobler
Scoobler

Reputation: 9719

If you want to just target a button:

$('#buttonID').click(function(){
    $(this).attr('disabled', 'disabled');
});

If you want a function:

function diableButton(bID){
    $(bID).attr('disabled', 'disabled');
}

Call it using something like:

$('#myform').submit(function(){
    disableButton($('input[type=submit]', this));
});

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816364

The button must be an input element (if you don't submit the form via JavaScript). A <button> element has no attribute type and setting it will have no effect.
I also suggest to attach the click handler via jQuery:

<form>
    <!-- ... -->
    <input id="submit" type="submit" value="post" />
</form>
<script type="text/javascript>
    $('#submit').click(function() {
        $(this).attr('disabled', true);
    });
</script>

Reference: click, attr

Upvotes: 4

Scott Evernden
Scott Evernden

Reputation: 39950

$(button).attr('disabled', true);

Upvotes: 2

Mikhail
Mikhail

Reputation: 9007

<button onclick="this.disabled='disabled'" type...>

Upvotes: 0

Related Questions