0

I need to be able to submit a form only when a button is clicked. Also I need to disable the button once the form is submitted.

I was thinking of adding an id to the button and adding an on click function. Am I on the right track? Still not sure how to disable the button after it is actually clicked.

$('#myButton').click(function() {

});

2 Answers 2

2

You're on the right track. To disable the button after clicking, you just need to set the disabled attribute. Something like

$('#myButton').click(function() {
    // get a reference to the element on which the handler is bound
    // wrap it in a jQuery object so we can call jQuery methods on it.
    $(this)
    // set the disabled attribute. You can use true or the string 'disabled'
    .attr('disabled', true);
});

Bear in mind that a form can also be submitted by pressing the Enter key when an element inside the form has focus.

Sign up to request clarification or add additional context in comments.

6 Comments

Or simply: $(this).attr('disabled', true).closest('form').submit(); Yay for chaining!
@Adam - yep! I couldn't remember if attr returned the original object. Will update :)
I would go on to say further that you do not need to call .submit() on the form. Might need a fiddle to prove, but as long as you don't stop propagation or return false, the default action should occur (which is to submit the form). Without returning false on your function, you may actually be submitting the form twice if that's the case.
I am trying to avoid refresh -> submit in this particular page I can not use the method of re-directing in order to clear $_POST but i am OK to make it available only when the button is clicked.
@Adam - very true. It's been a long day!
|
1
$('#myButton').click(function() {
   $(this).attr('disabled','disabled')
});

3 Comments

I had a healthy debate about this not long ago and I've come to appreciate $(this).attr('disabled', false) over the string value. You can set the string to anything and it'll work the same so it's meaningless. Also, re-enabling is as easy as .attr('disabled', false) rather than removing the attribute entirely. Just food for thought.
Yup, it's one of those inconsistencies we need to live with, just like selected vs. checked.
It's not really inconsistent. .attr('disabled', false) is more consistent as you're doing DOM manipulation. And the W3C standards for the disabled DOM attribute is of type Boolean, not string.

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.