Search code examples
jqueryajaxposttogglestates

jquery toggle between 3 states and post a ajax call?


I need to toggle between 3 states

  • state #1: Unselected just grey background
  • state #2: Selected set background to green
  • state #2: Clicked again, set background to red Now on every click toggle between red and green

How would this be possible? Beside changing a class I also need to make an ajax call at the same time.

What I basically just want is a selected, not selected toggle and I have no idea how to detect is a user clicked the grey box the first time

For starters I now have:

<div id="test" onclick => "$(this).toggleClass('selected_yes')"> test <div>

Solution

  • Well you can still use toggle:

    $('#test').click(function() {
        if (this.className.match(/green|red/)) $(this).toggleClass('green red');
        else  $(this).toggleClass('green');
    
        // ajax call here
    });​
    

    http://jsfiddle.net/DRZY2/