Reputation: 47
I have 6 buttons and I wish to create a master button which will turn all the other buttons on or off. I managed to do that but ran into a problem when the master button would turn a button off if it was already on. I need this button to turn all the buttons on or off regardless of its previous state.Button 7 will be acting as master button. Thank you for taking the time to read this, any help would be much appreciated.
//master button
function button7(){
currentvalue = document.getElementById('button7').value;
if(currentvalue == "Off"){
document.getElementById("button7").value="On";
}else{
document.getElementById("button7").value="Off";
}
}
$(document).ready(function(){
$('#button7').on('click', function(){
$('#button7').toggleClass('on');
$('#button1').toggleClass('on');
$('#button2').toggleClass('on');
$('#button3').toggleClass('on');
$('#button4').toggleClass('on');
$('#button5').toggleClass('on');
$('#button6').toggleClass('on');
if(currentvalue == "Off"){
alert("off")
}
else{
alert("on")
}
});
});
//regular button
function button1(){
currentvalue = document.getElementById('button1').value;
if(currentvalue == "Off"){
document.getElementById("button1").value="On";
}else{
document.getElementById("button1").value="Off";
}
}
$(document).ready(function(){
$('#button1').on('click', function(){
$(this).toggleClass('on');
if(currentvalue == "Off"){
alert("off")
}
else{
alert("on")
}
});
});
Upvotes: 0
Views: 308
Reputation: 700302
Toggle the class on the button, the check if it has that class and use that to add or remove the class on all the other buttons. Using a boolean value as the second parameter to toggleClass
will add or remove the class according to the boolean, not the presence of the class.
$(document).ready(function(){
$('#button7').on('click', function(){
$('#button7').toggleClass('on');
var currentvalue = $('#button7').hasClass('on');
$('#button1').toggleClass('on', curentvalue);
$('#button2').toggleClass('on', curentvalue);
$('#button3').toggleClass('on', curentvalue);
$('#button4').toggleClass('on', curentvalue);
$('#button5').toggleClass('on', curentvalue);
$('#button6').toggleClass('on', curentvalue);
if (currentvalue){
alert("on")
} else {
alert("off")
}
});
});
Upvotes: 1
Reputation: 253318
If you want to set all the buttons to a specific state, don't use toggleClass()
which, as the name itself suggests, is used to toggle class-names. Instead:
$('#button7').on('click', function(){
// select all the elements by their id:
$('#button1,#button2,#button3')
// remove both classes:
.removeClass('on off')
// add the class that the clicked-button currently represents:
.addClass(this.value)
// whatever Boolean the button currently represents,
// switch to the other option:
.val(this.value === 'On' ? 'Off' : 'On');
});
References:
Upvotes: 2