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();
This should be OK as a replacement to your
bindButtonsfunction meat.jsFiddle
It’s perfectly readable for me, but it might not be for you, so this might be better if you’d like: