HIRA THAKUR
HIRA THAKUR

Reputation: 17757

Jquery .off and then restore it to on

When i want to remove the click handler from my submit button,I am using

$(#submitBtn).off();//works fine

But,when I want to restore back to its previous stage,.on() doesnt work.

                if(flag){
               $(#submitBtn).off();//works fine
                $.ajax({
                    type: 'POST',
                    url: 'someservice.php',
                    data: {email:email,name:name,text:text},
                    success: function (data) {
                       $('#submitBtn').on();//does not work
                });//ajax end
            }

Upvotes: 0

Views: 1189

Answers (2)

Shaunak D
Shaunak D

Reputation: 20626

.off()

Calling .off() with no arguments removes all handlers attached to the elements. Specific event handlers can be removed on elements by providing combinations of event names, namespaces, selectors, or handler function names.

.on()

Attach an event handler function for one or more events to the selected elements. And it must have arguments -

.on( events [, selector ] [, data ], handler )

Instead of binding and unbinding, I suggest you use button disabling logic : .prop('disabled')

$('#submitBtn').prop('disabled',true)         //disable
$('#submitBtn').prop('disabled',false)        //enable

Note : The ID selector is written as $('#submitBtn') and not $(#submitBtn)

Upvotes: 1

Cjmarkham
Cjmarkham

Reputation: 9681

You are removing the event so when you call on() you need to specify which event since it won't know about it.

$('#submitBtn').on('click', someFn);

You could also disable the button to prevent multiple submits and then remove the disabled attribute in your ajax success handler

Upvotes: 0

Related Questions