jQuery not only allows us to attach event handlers on the element and it also allows us to take control of the flow of the events.

Đang xem: How to disable click event using jquery

You can enable and disable an event whenever you want in your script.

When it’s required?

The event is no longer needed on the element.

jQuery has an on() and off() method that helps you to enable and disable your specific selector.

*

Contents

1. off() Method

It removes Event handler from the specified element.

Syntax –

$(selector).off ( event );Example

$(document).ready(function(){ // Remove click event from all paragraph elements $(“p”).off( “click” ); // Remove chanage event from Textbox id=”txt_username” $( “#txt_username” ).off(“change”); });

2. on() Method

This works opposite of the off() method, it attaches an Event handler to the selected element.

Syntax –

$( selector ).on(event, function);Example

$(document).ready(function(){ // Attach click event to all paragraph elements $(“p”).on( “click”,function(){ console.log(“paragraph click”); } ); // Attach keyup event to Textbox id=”txt_username” $( “#txt_username” ).on(“keyup”,usernameChange); });function usernameChange(){ var value = $(this).val(); console.log(value);}

3. Example

In the example, I am creating a Textbox and a Button. Defining change event on Textbox in jQuery.

Xem thêm: Tải Game Siêu Nổ Ota – Sieuno Nohu888 Cổng Game Quay Hũ Thời Thượng

When the input value is less than 18 then remove the click event from the button otherwise, it prints the entered age on the screen.

Age should be greater than 18

4. Demo

Enter your Age in the Textbox and click Submit Button.

5. Conclusion

I showed how you can enable disable an event handler from the element. By this, you can restrict when the event will trigger or disable.

If you are using AJAX for saving data and want the user only able to click once on the button, in this case, you can either remove the click event or add a disabled attribute.

If you found this tutorial helpful then don”t forget to share.

Xem thêm:

Previous PostHow to Highlight Selected date in jQuery UI Datepicker

Next PostHow to make Pull Down to Refresh Webpage with jQuery

*

Yogesh Singh is a web developer and founder of darkedeneurope.com .He mainly blogs about PHP, AJAX, JavaScript, jQuery, AngularJS, Database, Python, and something that interest him.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *