0

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'.

0

4 Answers 4

2
$(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/

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

Comments

1

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

Comments

1

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

Comments

0
 $(".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)

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.