Input only with V or F

0

Is it possible to put an input where it only receives (V) or (F)?

<script type="text/javascript">
    jQuery(function($){
        $("#resposta_vouf").mask("(a)");   
    });
</script>

<input type="text" id="resposta_vouf" />
    
asked by anonymous 15.03.2015 / 08:50

1 answer

1

I have. First I started from this one from Stack Overflow . After that, I tried the code and got there:

var valorSalvo = 'F';

$('#textbox').on('input propertychange paste', function() {
   var atual = $("#textbox").val().replace(/v/g, 'V').replace(/f/g, 'F').replace(/[^VF]/g, '');
   var ultimo = atual.substring(atual.length - 1);
   var primeiro = atual.substring(0, 1);
   var novo = ultimo === valorSalvo ? primeiro : ultimo;
   if (novo === 'V' || novo === 'F') valorSalvo = novo;
   $("#textbox").val(valorSalvo);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="textbox" type="text" value="F" />

The algorithm works like this:

  • The field starts with F . It is not imperative that it start with a valid value, but it is strongly recommended.

  • Initially, the program will allow the textbox to be changed in any way (either by typing or using Ctrl + V ), but the change will not be visible and will not take effect because the event (which will reset the contents of the input) is fired immediately after that.

  • The characters v s and f s are converted to uppercase and the different characters of V and F are removed.

  • The algorithm attempts to determine whether the old text is at the beginning or end of the new text to see if what was typed or pasted is at the beginning or end, and uses this to detect which new character it is interests.

  • If the resulting text is F or V , this text will be applied to the input (overwriting what was there). Otherwise (the new text may be empty, for example), the previous text is applied (also overwriting what is in the input) and therefore resulting in rejection of the change.

  • There's an important detail to note: Since I'm not doing keystrokes, as would be the case if I used keydown or keypress , then I do not have to worry about backspace and special keys. As a result, this code works with Ctrl + A , Ctrl + C , Ctrl + V and Ctrl + X and also does not block any special keys such as Home , Tab and directional arrows.

        
    15.03.2015 / 10:27