views:

26

answers:

1

I've got about 20 on/off switches that sends an ajax request which updates a field in a table. I've duplicated where the class attaches to the selector because i need to be able to designate which switches are on or off. However, the first button i click on works, but after that, i sometimes need to click once for some of the other buttons, while the rest require two clicks. Here's some code!

attaching the class:

$(document).ready(function() {
    var user = $(".profile").attr('id');
    $('#status').hide();
    $('.switch1').checkbox("on", 
     function(theId) {
      $.post("setPerms.php", { user_id: user, val: "1", field: theId }, function(data){
       $("#status").text(data).fadeIn(1000);
       $('#status').fadeOut(1000);
      });
      },
     function(theId) {
      $.post("setPerms.php", { user_id: user, val: "0", field: theId }, function(data){
       $("#status").text(data).fadeIn(1000);
       $('#status').fadeOut(1000);
      });
     });

    $('.switch0').checkbox("off", 
     function(theId) {
      $.post("setPerms.php", { user_id: user, val: "1", field: theId }, function(data){
       $("#status").text(data).fadeIn(1000);
       $('#status').fadeOut(1000);
      });
       },
     function(theId) {
      $.post("setPerms.php", { user_id: user, val: "0", field: theId }, function(data){
       $("#status").text(data).fadeIn(1000);
       $('#status').fadeOut(1000);
      });
     });
});

and here is where the clicking functionality is: (seperate files)

// click handling
     jQuery(this).click(function() {
      var theId = $(this).attr('id');
      if(state == 'on') {
       jQuery(this).find('.iphone_switch').animate({backgroundPosition: -53}, "normal", function() {
        jQuery(this).attr('src', settings.switch_off_container_path);
        switched_off_callback(theId);
       });
       state = 'off';
      }
      else {
       jQuery(this).find('.iphone_switch').animate({backgroundPosition: 0}, "normal", function() {
        switched_on_callback(theId);
       });
       jQuery(this).find('.iphone_switch').attr('src', settings.switch_on_container_path);
       state = 'on';
      }
     });

let me know if you need more information. any help is greatly appreciated!!

A: 

It looks like you have a global state variable instead of a state variable specific to each switch. You should add an attribute to each switch called state and check that.

Tim
i think that's it, but how do i go about adding the attr?
mlebrun15
ok got it. just used the data() function to store the state variable. thanks again.
mlebrun15