简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM