Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create efficient code for a toggle between two buttons in Javascript using jQuery?

I'm looking for a way to toggle between two buttons efficiently using javascript and jQuery.

Scope

When clicking on either Yes or No, the opposite button will get a disabled CSS class while the clicked button will get an active CSS class. A var will also be saved with a true false value that will be used later.

html

<div id="buttons">
  <button id="yes">Yes</button>
  <button id="no">No</button>
</div>

js

function bindButtons(){
  var buttons = $('#buttons button');

  buttons.on('click', function(e){
    var $this = $(this);
    buttons.removeClass('selected');
    if($this.attr('id') == 'yes'){
      var el = $('#no'),
          val = true;
      $this.removeClass('disabled');
      $this.addClass('selected');
      el.addClass('disabled');
    }
    if($this.attr('id') == 'no'){
      var el = $('#yes'),
          val = false;
      $this.removeClass('disabled');
      $this.addClass('selected');
      el.addClass('disabled');
    }
    //do something with val
  })
}
bindButtons();

jsFiddle

http://jsfiddle.net/RobertSheaO/Tjngw/2/


1 Answers

This should be OK as a replacement to your bindButtons function meat.

EDIT

Apparently, this should also work with more than one button. Late night coding as well. >_>

var buttons = $('#buttons button').on('click', function (e) {

    var $this = $(this).removeClass('disabled').addClass('selected'),
        el = buttons.not(this).addClass('disabled'),
        isYes = $this.is('#yes')
        ;

    // do something with isYes

});

jsFiddle

It's perfectly readable for me, but it might not be for you, so this might be better if you'd like:

var buttons = $('#buttons button').on('click', function (e) {

    var $this = $(this),
        el = buttons.not(this),
        isYes = $this.is('#yes')
        ;

    $this.removeClass('disabled');
    $this.addClass('selected');
    el.addClass('disabled');

});
like image 68
Richard Neil Ilagan Avatar answered Sep 07 '26 10:09

Richard Neil Ilagan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!