Shawn Cooke
Shawn Cooke

Reputation: 967

jQuery use button for multiple click events

I would like to be able to click a button to enable a text input for editing and then click it again when I am done which will fire off the ajax to save it. I am reading the doc's for on() and off() and am unable to get this to work. Here is the code:

 <div>
   <button>Click Me!</button>  
 </div>

$('button').click(function(){
   //add a class as a handle for the save event later
   $(this).addClass('test').text('Click to Save');
   //remove the click event from the button
   $(this).off('click');
   alert("This event is off!");
   //do other stuff like disable the input (no help needed)
});
$("div").on("click","button.test" function(){
   alert("This event works!");
   //do ajax stuff here (no help needed)

   //turn this event off and turn the other back on??
});

Upvotes: 1

Views: 293

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240888

It's because $(this).off('click') will remove all click events from the element.

There are a couple ways to work around this, but I'd suggest putting the events in a namespace so that you can remove the desired one.

For example, .off('click.one') would remove an event attached with .on('click.one').

$('button').on('click.toggleInput', toggleInput);
$("div").on("click.saveForm", "button.test", saveForm);

function toggleInput () {
  $(this).addClass('test').text('Click to Save');
  $(this).off('click.toggleInput');

  // Do other stuff
}

function saveForm () {
  $(this).removeClass('test');
  $(this).on('click.toggleInput', toggleInput);

  // Do other stuff
}

Depending on what you're trying to achieve, you could also use the .one() method in order to attach an event that only gets fired once.

Upvotes: 2

Related Questions