I'm looking for a way to toggle between two buttons efficiently using javascript and jQuery.
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.
<div id="buttons">
<button id="yes">Yes</button>
<button id="no">No</button>
</div>
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();
http://jsfiddle.net/RobertSheaO/Tjngw/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');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With