April 16, 2012

Adding two click events to the same button only works once

Question by bob_cobb

Basically I’m trying to make a button be able to handle editing of an element. I want it so that when I click on the Edit button, it changes the text to Save Changes and adds a class which will then bind the button to another click event so that when they click Save Changes, it’ll alert Saved and change the text back to Edit. It does this perfectly once. If you continue to try to do it, it simply won’t add the class or change the text anymore.

Here is a demo on jsfiddle

The code:

$(function() {
$button = $('button[name="edit"]');
$button.on('click', $button, function() {
    var $that = $(this);
    $that.text('Save Changes');
    $that.addClass('js-editing');
    if ($that.hasClass('js-editing')) {
        $that.off('click').on('click', $that, function() {
            alert('Saved!');
            $that.text('Edit');
            $that.removeClass('js-editing');
        });
    }
});

});​

Answer by qw3n

Try this http://jsfiddle.net/bpD8B/4/

$(function() {
    $button = $('button[name="edit"]');
    $button.on('click', $button, function() {
        var $that = $(this);
        if($that.text()=='Edit'){
          $that.text('Save Changes');
          $that.addClass('js-editing');
        }
        else{
                alert('Saved!');
                $that.text('Edit');
                $that.removeClass('js-editing');
        }
    });
});

Answer by Starx

This is just a logic problem. And with $that.off('click').on('click', $that, function() { you are delegating to itself, which is not how you should do it.

Here is a solution using your code:

$(function() {

    $button = $('button[name="edit"]');
    $button.on('click', $button, function() {
        var $that = $(this);
        if ($that.hasClass('js-editing')) {
            alert('Saved!');
            $that.text('Edit');
            $that.removeClass('js-editing');        
        } else {      
            $that.text('Save Changes'); 
            $that.addClass('js-editing');
        }
    });

});​

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!