javascript – Remove the last input typed in a form with multiple responses

Question:

I have a 10-answer form on which a person must put only 3 responses.

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

Here is my code:

It actually works, but the problem is that it doesn't erase the last input typed depending on the order I'm going to fill it.

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("");
                }

        }
    }

});

Answer:

Looking at your code I suggest doing it in a cleaner/simple way:

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: http://jsfiddle.net/4bq3mgvu/

This way, every time you click it calls all inputs that have a name starting with resposta :

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

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

Then you check if those that are filled are more than 3 with if (respondidas.length > maxRespostas) , and if true with .slice(3) it removes the first 3 from this collection and erases the value of the rest.

Scroll to Top