Change class of a Button when it is disabled and vice versa

1

Good afternoon, guys I have a form with 2 inputs that I have to fill in to enable button . I wanted the button to have a color when disabled and another color when I had enabled it.

I'll show the code that enables my button and the code I tried to change his class when enabled and disabled, but it did not work!

JavaScript:

$(function() {
    var $inputs = $("#input-1,#input-2", "#formAdm"),
        $button = $("#btn_adm");

    var limpos = 0;

    // contagem inicial de valores não preenchidos
    $inputs.each(function() {
        var $this = $(this);
        var val = $this.val();
        val || limpos++;
        $this.data("val-antigo", val);
    });

    $button.prop("disabled", !!limpos);

    $inputs.on("change keyup mouseup", function() {

        var $this = $(this);
        var val = $this.val();
        limpos += (val ? 0 : 1) - ($this.data("val-antigo") ? 0 : 1);
        $this.data("val-antigo", val);
        $button.prop("disabled", !!limpos);
    });
});
$(document).ready(function() {
    if ($('#btn_adm:disabled')) {
        $('#btn_adm').addClass("btn_off");
        $('#btn_adm').removeClass("button_cad");
    } else {
        $('#btn_adm').addClass("button_cad");
        $('#btn_adm').removeClass("btn_off");
    }
});

HTML:

<form id="formAdm" action="" method="post">
    <center>
        <div class="linha_fila">
            <label>Usuário</label>
            <br>
            <input onkeyup="this.value=this.value.replace(/[' ']/g,''); c('input-1')" required class="inp_editar" type="text" name="usuario" id="input-1" />
        </div>
        <div class="linha_fila">
            <label>Senha</label>
            <br>
            <input required class="inp_editar" type="password" name="senha" id="input-2" />
        </div>
        <div class="linha_fila">
            <label>E-mail</label>
            <br>
            <input onkeyup="this.value=this.value.replace(/[' ']/g,'')" required class="inp_editar" type="email" name="email" id="input-3" />
        </div>
    </center>
    <button id="btn_adm" type="submit" class="button_cad">Salvar</button>
</form>
    
asked by anonymous 01.08.2016 / 18:18

1 answer

1

The best thing was to do this with CSS ...

button:disabled {
	color: red;
}
<button>Eu estou ativo</button>
<button disabled>Eu estou desativado</button>

If you want to do in JavaScript / jQuery you can use .toggleClass() , which inserts or removes the class according to the value of the second argument. Something like this (using what you already have in your code):

 $button.prop("disabled", !!limpos);
 $button.toggleClass("btn_off", !limpos);
 $button.toggleClass("button_cad", limpos);
    
01.08.2016 / 18:28