Input with V or F only

Asked

Viewed 137 times

0

You can place an input where it receives only (V) or (F)?

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

<input type="text" id="resposta_vouf" />
  • 1

    Wouldn’t it be easier to use one input type='checkbox'? When marked = true, otherwise = false.

  • If my answer pleased you, do not forget to accept it. :)

1 answer

1

I did it. First I started to leave of this other Stack Overflow in English. After that, I tried the code and came to this:

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>
<input id="textbox" type="text" value="F" />

The algorithm works like this:

  1. The field starts with the value F. It is not essential that it starts with a valid value, but it is highly recommended.

  2. 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 input content) is triggered immediately after that.

  3. The characters vs and flowercase s are converted to uppercase and those different from V and F are removed.

  4. The algorithm tries to determine whether the old text is at the beginning or at the end of the new text to determine whether the typed or pasted text is at the beginning or at the end, and uses this to detect which new character matters.

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

There is one important detail to note: As I am not doing keystroke filtering, so would be the case if I used keydown or keypress, so I don’t have to worry about Backspace and special keys. As a result, that code there works with Ctrl+A, Ctrl+C, Ctrl+V and Ctrl+X and also does not block any special key such as Home, Tab and directional arrows.

Browser other questions tagged

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