0

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);
   });
  });

Erik
  • 5,701
  • 27
  • 70
  • 119

3 Answers3

0

Something like this:

$(function(){
    $("input[type='button']").click(function() {
        if ($(this).hasClass("button-toggle-on")) {
            $(this).removeClass("button-toggle-on");
            $("#gender").val('');
        } else {
            $("input[type='button']").removeClass("button-toggle-on");
            $(this).addClass("button-toggle-on");
            if($(this).hasClass("gnF")) varval = 'female';
            else varval = 'male';
            $("#gender").val(varval);
        }
    });
});
Ilia Frenkel
  • 1,969
  • 13
  • 19
0

Take a look at this demo.

var $buttons = $("input[type='button']");
$buttons.click(function() {
    $buttons.not(this).removeClass('button-toggle-on');
    $(this).toggleClass('button-toggle-on');

    var varval = '';
    if ($(this).hasClass('button-toggle-on')) {
        varval = $(this).hasClass('gnF') ? 'female' : 'male';
    }
    $("#gender").val(varval);
});
dfsq
  • 191,768
  • 25
  • 236
  • 258
0

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");    
    }
  });
});
Neil
  • 51
  • 1
  • Works great but I can't get it to come to life on my page... Hmmm. must be a conflict somewhere – Erik Apr 13 '12 at 06:08
  • @Erik There is a good chance that firebug's console would tell you where the problem lies. – Joonas Apr 13 '12 at 06:28