Search code examples
javascriptjqueryinputtogglebackground-position

toggle background-position TWICE


I would like de-select the button by clicking the same button TWICE.

Once I click on Female or Male, the script changes the background-position and inserts the data into the gender input correctly, but I would like to return the same button to its original position if clicked again (twice) AND remove the result in the gender input field.

Can anyone suggest a modification to my script?

Should this be a separate script?

Thanks

http://jsfiddle.net/B4XkL/5/

 $(function(){
    $("input[type='button']").click(function() {
      $("input[type='button']").removeClass("button-toggle-on");
        $(this).addClass("button-toggle-on");
    if($(this).hasClass("gnF")) varval = 'female';
  else varval = 'male';
    $("#gender").val(varval);
   });
  });


Solution

  • This'll do the trick:

    $(function(){
        $("input[type='button']").click(function() {
    
        if($(this).hasClass("button-toggle-on")) {
            $(this).removeClass("button-toggle-on");
            $("#gender").val("");                
        }
        else {
            $(".button-toggle-on").removeClass("button-toggle-on");                    
            $(this).addClass("button-toggle-on");
            $("#gender").val(($(this).hasClass("gnF"))? "female" : "male");    
        }
      });
    });