1

In my form, I have no.of form elements, I would like to remove all the listeners from the form elements.. how to achieve this?

here is my try, but not working..is this only way to remove each one by one?

    var testFunction = function () {
        $form = $('form'),
        $name = $form.find('#name'),
        $code = $form.find('#code'), //it will have more events..
        $city = $form.find('#city'), //it will have more events..
        $native = $form.find('#native'), //it will have more events..
        $gender = $form.find('#gender'), //it will have more events..
        $select = $form.find('#select'); //it will have more events..

//sample.

        $name.on('focus keydown input', function(e){
            console.log(e.target.value);
        });

        $select.on('change', function(e){
            console.log($(this).val());
        });
    }

    testFunction();

    $('#unbindForm').on('click', function(){
        $('form').addClass('highlight').off(); //i can't remove all events?
    });

what would be the correct approach. in the off do i need to send all listeners what i used? (change keydown input)?

Live Demo

3gwebtrain
  • 13,401
  • 21
  • 93
  • 195

2 Answers2

2

Demo Fiddle

Use .unbind() : With no arguments, .unbind() removes all handlers attached to the elements.

$('form *').unbind();

OR

Demo

$('form *').off();

For jQuery 1.7 > .off() is not available. Above 1.7, both the methods work. - Reference

Community
  • 1
  • 1
Shaunak D
  • 19,751
  • 9
  • 41
  • 72
  • I thought, even `off` will work so.. is it not? and it find each element right. is there any way to find listener alone and remove? – 3gwebtrain Jun 16 '14 at 06:00
1

If you want to remove all the events from the elements just use .off() without passing any anrguments into it.

$('form *:not(#name)').off();

And here I have excluded the element with id name since you said that it does not have any events at all.

DEMO

Rajaprabhu Aravindasamy
  • 63,064
  • 13
  • 90
  • 119