aronccs aronccs - 5 months ago 16
Javascript Question

Javascript change a button class onclick using "classList"

I want to change the appearance of two buttons when either one of them is clicked. But I cannot seem to do that.

I want the classes of the buttons to be changed every time a new button is clicked, but nothing is happening with this code. What could be the problem?

function offbutton() {
var offbtn = document.getElementById("btndisable3");
var onbtn = document.getElementById("btnenable3");

offbtn.classList.remove("btn btn-default");
offbtn.classList.add("btn btn-danger active");
onbtn.classList.remove("btn btn-success active");
onbtn.classList.add("btn btn-default");
}

function onbutton() {
var offbtn = document.getElementById("btndisable3");
var onbtn = document.getElementById("btnenable3");

onbtn.classList.remove("btn btn-default");
onbtn.classList.add("btn btn-success active");
offbtn.classList.remove("btn btn-danger active");
offbtn.classList.add("btn btn-default");
}


<div class="form-group">
<label class="col-sm-2 control-label">
<?=$ name ?>
</label>
<div class="col-sm-10">
<div class="btn-group" data-toggle="buttons">
<label id="btndisable<?= $id ?>" class="btn <?php if($value == 0){ echo 'btn-danger active'; } else{ echo 'btn-default'; } ?>" onclick="offbutton();">
<div class="col-sm-2">
<input type="radio" name="options<?= $id ?>" id="disable<?= $id ?>" value="0" <?php if($value==0 ){ echo 'checked'; } ?>> O
</div>
</label>
<label id="btnenable<?= $id ?>" class="btn <?php if($value == 1){ echo 'btn-success active'; } else{ echo 'btn-default'; } ?>" onclick="onbutton();">
<div class="col-sm-2">
<input type="radio" name="options<?= $id ?>" id="enable<?= $id ?>" value="1" <?php if($value=='1' ){ echo 'checked'; } ?>> I
</div>
</label>
</div>
</div>
</div>



Answer

You have to use comma , separator if you want to add/remove several classes so your code should be :

function offbutton() {
    var offbtn = document.getElementById("btndisable3");
    var onbtn = document.getElementById("btnenable3");

    offbtn.classList.remove("btn","btn-default");
    offbtn.classList.add("btn","btn-danger","active");
    onbtn.classList.remove("btn","btn-success","active");
    onbtn.classList.add("btn","btn-default");
}

function onbutton() {
    var offbtn = document.getElementById("btndisable3");
    var onbtn = document.getElementById("btnenable3");

    onbtn.classList.remove("btn","btn-default");
    onbtn.classList.add("btn","btn-success","active");
    offbtn.classList.remove("btn","btn-danger","active");
    offbtn.classList.add("btn","btn-default");
}

Hope this helps.

Comments