1

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??
});

1 Answer 1

2

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.

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

Comments

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.