Remove disabled attribute when a condition is satisfied

4

Good evening.

I'm trying to make a log and login screen for an application that will save the data to 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 disabled property is removed and the button can be clicked but I can not remove disabled , tried in many ways and nothing. I think 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 solve it? Thanks for the help.

    
asked by anonymous 15.04.2017 / 06:55

2 answers

3

You want when the field has the correct number of characters, it is enabled again right? Note that $(document).keyup(function(){}); will check every time 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: link

So try 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 do not know exactly what your needs are, but this verification 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 it can handle this, good that there is a server-side check as well. Since you are developing an application that uses 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 this and is developing something in PHP for example, and think that it will simply solve the problem.

    
15.04.2017 / 07:20
1

It's no use modifying the value of the disabled attribute to false.

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

So 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 re-enable your button is by removing the attribute. You can use the removeProp of jQuery function to do this. E.g.:

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

If you ever find a browser that enables an element that has the value of the disabled attribute 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: link

    
15.04.2017 / 14:08