Remove the last input typed in a form with multiple responses

Asked

Viewed 87 times

3

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

If she fills more than 3, the last input typed must be erased.

Just follow my code:

It kind of works, but the problem is it doesn’t erase the last input typed depending on the order I will fill in.

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

        }
    }

});

1 answer

1


Looking at your code I suggest you do it in a cleaner/simpler 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/

That way each time you click it calls all the inputs that have name starting with resposta:

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

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

Then check that the ones that are filled are more than 3 with if (respondidas.length > maxRespostas), and if it comes true with the .slice(3) it removes the first 3 from that collection and deletes the value of the remaining.

Browser other questions tagged

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