tatty27
tatty27

Reputation: 1554

Use the same button to trigger two different JQuery events

I am trying to use the same button to trigger an ajax call to add a database entry if it is clicked and then trigger a different ajax call to remove the entry it is clicked again.

I have tried using toggleClass and although the button class does change and it's appearance changes accordingly the function still thinks it has the old class name.

$(document).ready(function() { 
   $(".selected").on("click", function() {
       $(this).text(function (i, oldText) {
        return $.trim(oldText) == 'Use Image' ? 'Selected' : 'Use Image';   
    });
       $(this).toggleClass('selected selected_btn');
   });

   $(".selected").on("click", function() {
        alert('selected');
    });
   $(".selected_btn").on("click", function() {
        alert('de selected');
    });   
});

With the present code the alert is always 'selected'.

Upvotes: 0

Views: 1467

Answers (4)

Kevin Jantzer
Kevin Jantzer

Reputation: 9451

Here is a simple and readable example on how to do this:

$(document).ready(function() {

    $('.select-img').on('click', function(){

        var $el = $(this);
        var isSelected = $el.attr('data-selected');

        if( isSelected != 'true' ){
            firstFn();
            $el.html('Use Image').attr('data-selected', true)
        }else{
            secondFn();
            $el.html('Select').attr('data-selected', false)
        }

    })

    var firstFn = function(){
        alert('first thing to do');
    }

    var secondFn = function(){
        alert('second thing to do');
    }

})

Demo

Upvotes: 1

Sharikov Vladislav
Sharikov Vladislav

Reputation: 7269

Use *Class functions:

Working code:

$("a").on("click", function() {
    if($(this).hasClass("bob")) {
        // do delete
        alert("delete");
        $(this).removeClass("bob");
    } else {
        // do insert
        alert("insert");
        $(this).addClass("bob");
    }
});

Demo

Upvotes: 1

ProllyGeek
ProllyGeek

Reputation: 15836

$(document).ready(function() { 
   $(".selected_btn").on("click", function() {
       $(this).text(function (i, oldText) {
        return $.trim(oldText) == 'Use Image' ? 'Selected' : 'Use Image';   
    });
       $(this).toggleClass('selected');
  if($(this).hasClass("selected"))
      alert("Selected")
  else 
      alert("de-Selected")
   });
 });

here is a fiddle:

http://fiddle.jshell.net/prollygeek/3LLN2/

Upvotes: 2

Xesau
Xesau

Reputation: 161

 $(".selected").on("click", function() {
    alert('selected');
 });

Overrides the event you put on the beginning of the document.ready, I think. (might not be true, but I think it is)

Upvotes: 0

Related Questions