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

Asked

Viewed 792 times

1

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

I’ll show you the code that enables mine button and the code I tried to change his class when enabled and disabled, but it didn’t 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>

1 answer

2


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

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

If you want to do Javascript/jQuery you can use the .toggleClass(), which inserts or removes the class depending on 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);
  • 1

    Very obg guy, worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.