Bug in JQuery programming

1

Good evening! I have a problem in programming an exercise, I need to remove these spans from the missing fields in the input, leaving only one that changes as needed.

$(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><labelfor="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>
    
asked by anonymous 02.10.2016 / 00:06

1 answer

0

You need to clear the html from this field before putting back what is still missing. Using $("#validacao").html('') you delete old content.

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: link

$(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><labelfor="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>
    
02.10.2016 / 00:13