Bug in Jquery programming

Asked

Viewed 33 times

1

Good night! I have a problem in the programming of an exercise, I need to remove these "spans" from the fields that are missing in the input, leaving only one that changes according to the need.

$(document).ready(function() {
    $("#validar").click(function() {
        $("input").each(function(index, element) {
            if ($(element).val() == '') {
                $("#validacao").append(element.id + "<br>");
            }
        });
    });
});
div {
    width: 40px;
    height: 40px;
    margin: 5px;
    float: left;
    border: 2px blue solid;
    text-align: center;
}

span {
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <label for="nome">Nome</label>
    <input type="text" id="nome">
    <br>
    <label for="cpf">CPF</label>
    <input type="text" id="cpf">
    <br>
    <label for="rg">RG</label>
    <input type="text" id="rg">
    <br>
    <input style="color: #0026ff" type="button" id="validar" value="Validar !" />
    <br />
    <span id="validacao">Campos Inválidos<br /></span>
</form>

1 answer

0


You need to clear the html of that field before putting back what is still missing. Using $("#validacao").html('') delete the old contents.

You can do it like this:

$(document).ready(function() {
    var $validacao = $("#validacao");
    $("#validar").click(function() {
        $validacao.html('');
        $("input").each(function(index, element) {
            if (!element.value.trim()) {
                $validacao.append(element.id + "<br>");
            }
        });
    });
});

jsFiddle: https://jsfiddle.net/hmd7s2bw/

$(document).ready(function() {
    var $validacao = $("#validacao");
    $("#validar").click(function() {
        $validacao.html('');
        $("input").each(function(index, element) {
            if (!element.value.trim()) {
                $validacao.append(element.id + "<br>");
            }
        });
    });
});
div {
    width: 40px;
    height: 40px;
    margin: 5px;
    float: left;
    border: 2px blue solid;
    text-align: center;
}

span {
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <label for="nome">Nome</label>
    <input type="text" id="nome">
    <br>
    <label for="cpf">CPF</label>
    <input type="text" id="cpf">
    <br>
    <label for="rg">RG</label>
    <input type="text" id="rg">
    <br>
    <input style="color: #0026ff" type="button" id="validar" value="Validar !" />
    <br />
    <span id="validacao">Campos Inválidos<br /></span>
</form>

Browser other questions tagged

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