1

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!

JasCav
  • 34,458
  • 20
  • 113
  • 170
Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378

4 Answers4

4

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
2
$(button).attr('disabled', true);
Scott Evernden
  • 39,136
  • 15
  • 78
  • 84
0
<button onclick="this.disabled='disabled'" type...>
Mikhail
  • 8,692
  • 8
  • 56
  • 82
0

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));
});
Scoobler
  • 9,696
  • 4
  • 36
  • 51
  • I don't understand why you'd use a wrapper function for `.attr('disabled','disabled')` if you're doing a jQuery `.submit()`. – user113716 Jan 31 '11 at 15:59
  • Tbh only because the user asked for a function, if you had multiple forms on one page and you only wanted to disable the form button: see the example here: http://jsfiddle.net/Scoobler/nKkKR/1/ you could be using an ajax call within the .submit() so you don't the button being pressed again for that form. – Scoobler Jan 31 '11 at 16:18