Remove disabled attribute when a condition is met

Asked

Viewed 4,666 times

4

Good night.

I am trying to make a login and registration screen for an application that will save the data in localStorage. To prevent the user from registering with incomplete data I disabled the Submit button using disabled.

My intention is when all fields are filled in the property disabled is removed and the button can be clicked but I cannot remove the disabled, tried several ways and nothing. I believe the easiest way would be this:

var operacao = "A"; //"A"=Adição; "E"=Edição
var indice_selecionado = -1; //Índice do item selecionado na lista
var tbUsuarios;

//aqui o botão submit já está desabilitado
$(document).ready(function() {
    $('#buttonSubmitRegister').prop('disabled', true);
});

$(function () {
    tbUsuarios = localStorage.getItem("tbUsuarios");// Recupera os dados armazenados
    tbUsuarios = JSON.parse(tbUsuarios); // Converte string para objeto
    if (tbUsuarios === null) // Caso não haja conteúdo, iniciamos um vetor vazio
        tbUsuarios = [];
});

function Adicionar() {
    var usuario = JSON.stringify({
        Nome: $("#txtNome").val(),
        email: $("#txtEmail").val(),
        Senha: $("#txtSenha").val()
    });
    //aqui tentei remover o disabled quando os campos forem preenchidos
    if ($("#txtNome").val().length > 1 && $("#txtEmail").val().length > 1 && $("#txtSenha").val().length > 1){
        $(document).ready(function() {
            $('#buttonSubmitRegister').prop('disabled', false);
        });
        tbUsuarios.push(usuario);
        localStorage.setItem("tbUsuarios", JSON.stringify(tbUsuarios));
        alert("Usuário Cadastrado com Sucesso!");
        return true;
    }
}
<form id="formRegister" nome="formRegister" class="positionFormRegister">
                <div class="input-group">
                    <span class="input-group-addon"></span>
                    <label for="txtNome"></label>
                    <input id="txtNome" name="txtNome" type="text" class="form-control" placeholder="Crie seu nome de Usuário" autocomplete="off">
                </div>
                <div class="input-group">
                    <span class="input-group-addon"></span>
                    <label for="txtEmail"></label>
                    <input id="txtEmail" name="txtEmail" type="text" class="form-control" placeholder="Seu endereço de e-mail" autocomplete="off">
                </div>
                <div class="input-group">
                    <span class="input-group-addon"></span>
                    <label for="txtSenha"></label>
                    <input id="txtSenha" name="txtSenha" type="password" class="form-control" placeholder="Crie sua senha" autocomplete="off">
                </div>
                <!--Botão Submit-->
                <div>
                    <input id="buttonSubmitRegister" type="submit" class="btn btn-primary btn-lg positionFormRegister" value="Cadastrar no e-Pro &raquo;" onclick="Adicionar()">
                </div>
            </form>

Does anyone have any idea how to fix it? Thanks for the help.

  • I also tried with ' $("#txtNome"). val(). length != " " '. But it didn’t work

2 answers

3


Do you want when the field has the correct number of characters, it is enabled again right? Note that the $(document).keyup(function(){}); will check whenever a key is pressed. My example code:

$(document).keyup(function() {
    if($("#email-test").val().length > 0 && $("#password-test").val().length > 0) {
        $(document).ready(function() {
            $('#submit-test').prop('disabled', false);
        });
    }
});

Example in jsfiddle: https://jsfiddle.net/Knautiluz/L9vqatoh/2/

Try this with the event outside the add function, otherwise it will only be computed when the function is triggered:

var operacao = "A"; //"A"=Adição; "E"=Edição
var indice_selecionado = -1; //Índice do item selecionado na lista
var tbUsuarios;

//aqui o botão submit já está desabilitado
$(document).ready(function() {
  $('#buttonSubmitRegister').prop('disabled', true);
});

$(function() {
  tbUsuarios = localStorage.getItem("tbUsuarios"); // Recupera os dados armazenados
  tbUsuarios = JSON.parse(tbUsuarios); // Converte string para objeto
  if (tbUsuarios === null) // Caso não haja conteúdo, iniciamos um vetor vazio
    tbUsuarios = [];
});

function Adicionar() {
  var usuario = JSON.stringify({
    Nome: $("#txtNome").val(),
    email: $("#txtEmail").val(),
    Senha: $("#txtSenha").val()
  });
}



$(document).keyup(function() {
  // habilita caso o numero de caracteres seja maior que 1.
  if ($("#txtNome").val().length > 1 && $("#txtEmail").val().length > 1 && $("#txtSenha").val().length > 1) {
    $(document).ready(function() {
      $('#buttonSubmitRegister').prop('disabled', false);
    });
    tbUsuarios.push(usuario);
    localStorage.setItem("tbUsuarios", JSON.stringify(tbUsuarios));
    alert("Usuário Cadastrado com Sucesso!");
    return true;
  }
  // desabilita o campo o valor seja apagado.
  if ($("#txtNome").val().length < 1 && $("#txtEmail").val().length < 1 && $("#txtSenha").val().length < 1) {
    $(document).ready(function() {
      $('#buttonSubmitRegister').prop('disabled', true);
    });
  }
});

I don’t know exactly what your needs are, but this check can be easily removed by the user, of course it will greatly decrease the number of registrations made missing some data... but if it is a malicious user he can manipulate it, then it is good that there is a check on server side as well. How are you developing an application that uses the localStorage I do not know if there is much that can be done. But I give this tip also if in the future someone finds it and is developing something in PHP for example, and think that simply this will solve the problem.

1

No use changing the value of the attribute disabled for fake.

Browsers do not read the value of the attribute. They only consider its presence. If the attribute exists, the element that has it is disabled. If attribute does not exist, element is not disabled.

Therefore, the four forms below are equivalent:

<input type="button" disabled>
<input type="button" disabled="true">
<input type="button" disabled="false">
<input type="button" disabled="Fui na Espanha buscar o meu chapéu, azul e branco da cor daquele céu"> <!--Ou qualquer outra canção de sua preferência-->

The only way to rehabilitate your button is by removing the attribute. You can use the function removeProp jQuery for that. E.g.:

$("#buttonSubmitRegister").removeProp("disabled");

If you ever find a browser that enables an element that has the attribute value disabled equal to false, know that this browser does not follow the HTML 5 specification:

The presence of a Boolean attribute on an element represents the true value, and the Absence of the attribute represents the false value.

"The presence of a boolean attribute in an element represents the true value and the absence of the attribute represents the false value".

Source: https://www.w3.org/TR/html5/infrastructure.html#Boolean-attribute

  • The idea is good, but it has this: "Also note that the . removeProp() method should not be used to set These properties to false. Once a Native Property is Removed, it cannot be Added Again. See . removeProp() for more information. "

  • Interesting this one, but seeing from this side, none of my browsers including Chrome and Firefox that are updated follow this rule, the only outdated one is IE, and in it also works.

  • 1

    From what I understand of this passage, any value within the disabled changes the condition to true, in the absence is false that is to say $("#elemento").prop('disabled', ""); also enable the element again. Then it would not be necessary to removeProp("disabled") correct?

Browser other questions tagged

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