admin管理员组

文章数量:1287517

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

/

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/RobertSheaO/Tjngw/2/

Share Improve this question edited Jan 15, 2013 at 13:06 hitautodestruct 20.8k14 gold badges75 silver badges95 bronze badges asked Jan 15, 2013 at 12:37 user888750user888750 3
  • 3 Please include all relevant code in your post and don't just include a link to jsFiddle. Link only posts are explicitly discouraged on Stack Exchange as your post should stand alone from any other resource; consider what'd happen if jsFiddle went down in the future! – Matt Commented Jan 15, 2013 at 12:37
  • 1 + what makes you think this is hugely inefficient? Have you seen this code impacting your UI responsiveness? – Matt Commented Jan 15, 2013 at 12:39
  • jQuery has a radiobutton option if that fits your needs. jQuery Button – atomman Commented Jan 15, 2013 at 12:51
Add a ment  | 

8 Answers 8

Reset to default 2

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

});

I suggest using the html5 data- attribute in your html for the answer and some jquery toggeling.

html

<div id="buttons">
    <button id="yes" data-answer="true">Yes</button>
    <button id="no" data-answer="false">No</button>
</div>

Toggeling is easy using jQuery:

Javascript

// Bind events to your buttons
var bindButtons = function(){

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

        e.preventDefault();

        $(this)
            .addClass('selected');
            .siblings()
            .removeClass('selected')
            .addClass('disabled');
    });

};

// Init binding
bindButtons();

// Get your answer
var answer = $('#buttons .selected').data('answer');

Demo

Try it on jsbin.

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

  buttons.on('click', function(e){
    var $this = $(this);
    buttons.removeClass('selected').addClass('disabled');
    $this.addClass('selected').removeClass('disabled');

    switch ($this.attr('id')){
        case 'yes': 
            val = true;
            break;
        case 'no': 
            val = false;
            break;
    }
    //do something with val
  })
}
function bindButtons(){
  $('#buttons button').click(function(e){ 
    var thisObj = $(this);
    $('#buttons').removeClass('selected');
    thisObj.removeClass('disabled').addClass('selected').siblings().addClass('disabled');
    var val = thisObj.attr('id')=='yes' ? true : false;    
    //do something with val
  })
}
bindButtons();

http://jsfiddle/Tjngw/6/

You can do things like shortening:

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

to:

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

And probably change the second if(){ to an else{

Apart from shortenings like that, unless this code is dragging the browser down (which is isn't) then there's nothing wrong with it.

You could try something like this:

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

  buttons.on('click', function(e){
    var $this = $(this);
    var el = $this;
    var val = $this.attr('id') === 'yes';
    buttons.removeClass('selected disabled');
    $this.addClass('selected')
      .siblings('button').addClass('disabled');

    //do something with val
  })
}

It at least removes the if statement.

Hopefully this helps a little. I usually use jQuery's .not() with $(this).

$('#buttons button').click(function() {
    $('#buttons button').not($(this)).removeClass('enabled').addClass('disabled');
    $(this).removeClass('disabled').addClass('enabled');

    var selected = $(this).attr('id'); // To use the id, or to use text use:
    var selected = $(this).text();  // No need for ids, grabs the text of element
});

Try this:

$("#buttons button").on('click', function(e) {
    $(".selected").removeClass('selected');

    var el;

    if($this.attr('id') == 'yes'){
        val = true;

        el = $("#no");
    } else {
        val = false;

        el = $("#yes");
    }

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

本文标签: How do I create efficient code for a toggle between two buttons in Javascript using jQueryStack Overflow