Remove the last entry entered in a form with multiple answers

3

I have a 10-question form in which the person should put only 3 answers.

If it fills more than 3, the last input entered should be deleted.

Here is my code:

It even works, but the problem is that it does not delete the last input entered depending on the order that I will fill.

HTML

<input type="text" name="resposta1">
<input type="text" name="resposta2">
<input type="text" name="resposta3">
<input type="text" name="resposta4">
<input type="text" name="resposta5">
<input type="text" name="resposta6">
<input type="text" name="resposta7">
<input type="text" name="resposta8">
<input type="text" name="resposta9">
<input type="text" name="resposta10">
<input type="button" id="btn-bloco" value="Aperte">

Javascript

var totalDeRespostas = 10;

$("#btn-bloco").on("click",function(){
    var totalDeRespostasRespondidas = 0;
    for(var i = 0; i< totalDeRespostas;i++){
        if($("[name='resposta"+(i+1)+"']").val() != ""){                   
                totalDeRespostasRespondidas++;
                if(totalDeRespostasRespondidas > 3){
                    var aux = $("[name='resposta"+(i+1)+"']").val();
                    alert(aux);

                    $("[name='resposta"+(i+1)+"']").val("");
                }

        }
    }

});
    
asked by anonymous 10.05.2015 / 02:55

1 answer

1

Looking at your code I suggest doing it cleanest / simplest:

var maxRespostas = 3;

$("#btn-bloco").on("click", function () {
    var respondidas = $('input[name^="resposta"]').filter(verificarValue);
    if (respondidas.length > maxRespostas) respondidas.slice(3).val('');
});

function verificarValue(i, input) {
    var value = input.value.split(' ').join('');
    return value;
}

jsFiddle: link

In this way every time you click it it calls all inputs that have names starting with resposta :

$('input[name^="resposta"]')

then filter them according to the value leaving the ones that are answered in a collection ( respondidas ). To filter I have used input.value.split(' ').join(''); which in the background deletes whitespace so it does not validate an input that may have white space but is in practice empty.

    
10.05.2015 / 05:23