Enter value "X" after some characters

1

In my form, you have textarea and would like to add the character X , without submitting the page, every 10 characters typed.

Example:

AAAAAAAAAA**X**BBBBBBBBBB**X**EEEEEEEEEE**X**12345678....

As the user typed in, he would enter every 10 characters. In this case, I do not need to mask, but rather add X to content.

Has anyone seen or done anything like this?

function mostrarResultado(box, campo_msg_contagem, campo_volumes_hidden) {
  var conteudo = document.getElementById('conteudo').value;
  var campo_caracteres = box.length;
  var tamanho_total_codbarras = document.getElementById('tamanho_codbarras').value;
  var resultado = 0;
  if (campo_caracteres > tamanho_total_codbarras) {
    resultado = Math.round(campo_caracteres / tamanho_total_codbarras);
    document.getElementById(campo_msg_contagem).innerHTML = "Lidos = " + resultado + "";
    document.getElementById(campo_volumes_hidden).value = resultado;
  } else {
    document.getElementById(campo_msg_contagem).innerHTML = "";
  }
}
<form name="form1" id="form1" action="teste.php" method="post">
  <textarea cols="50" id="conteudo" name="conteudo" rows="30" onkeyup="mostrarResultado(this.value, 'msg_contagem', 'volumes_hidden');"></textarea><br />
  <span id="msg_contagem" style="font-family:Georgia;"></span><br />
  <input type="hidden" id="tamanho_codbarras" name="tamanho_codbarras" value="10" />
  <input type="hidden" id="volumes_hidden" name="volumes_hidden" value="" />
  <input type="submit" /><br>
</form>

In this case, I took this function of counting characters and gave a basic change, which only adds +1 to every 10 characters entered, value set in input#tamanho_codbarras .

The goal is to break down the typed information on the next screen, with PHP explode function. In this case, my break control would be by the character X , using the example:

AAAAAAAAAA
BBBBBBBBBB
EEEEEEEEEE
12345678
    
asked by anonymous 20.09.2017 / 21:32

5 answers

2

var qtd = 10
var qtdX = 0

var div = document.getElementById('t')

div.onkeyup = function(){
  var valor = div.value
  
  if(valor.length == qtd + qtdX){
     qtd = qtd + 10
     qtdX = qtdX + 1
     div.value = valor + 'X'
  }
}
 

<textarea id="t"></textarea>

Would that be more or less?

    
20.09.2017 / 21:46
1

Compiling all the information I submitted:

The first, about using the jQuery library for such a trivial task. It is significantly increasing the payload of the application unnecessarily, worsening when system users have connection problems, such as commented . ( A joke on this subject to relax )

The second caution to be taken is with the event handled in JavaScript. I believe that the vast majority of bar code readers will paste the data into the field and, if so, the keypress , keyup and keydown events will not be triggered when a new bar code is read; only the paste event. However, if there are any players that trigger the first events, paste will not be triggered. That being said, the best JavaScript event that can be considered in this case is input . , because it is fired whenever the field value is changed, regardless of the source.

So, considering the following field in HTML:

<textarea name="conteudo" id="conteudo" rows="6" cols="50"></textarea>

We can start the JavaScript code:

const conteudo = document.getElementById("conteudo");

conteudo.addEventListener("input", function(event) {
  console.log(this.value);
});

For example, see working:

const conteudo = document.getElementById("conteudo");

conteudo.addEventListener("input", function(event) {
  console.log(this.value);
});
<textarea name="conteudo" id="conteudo" rows="6" cols="50"></textarea>

Whenever there is any change in the field content the new value will be displayed in the console. Now, just create the logic to separate the content into segments of size equal to 10. For this, we can use a very simple regular expression:

/.{1,10}/g

That is, take any character, other than the line break, in a sequence of 1 to 10 in length, as long as possible. Here's a simple example:

console.log("AAAAAAAAAABBBBBBBBBBEEEEEEEEEE12345678.".match(/.{1,10}/g))

From this, we can join with the previously created code and set the new value of the field. The logic will be very simple: whenever there is a change in the field, take the current value, separate into segments of length equal to 10 (or less), and add the character \n between them by setting the new value of the field. / p>

As I said, it will be interesting to use the \n character, since it is not visible and provides much better visual comfort by breaking the line with each new barcode.

The addition of the character between the segments can be done by the% method of the array :

console.log(['AAAAAAAAAA', 'BBBBBBBBBB', 'EEEEEEEEEE', '123'].join("\n"));

So, our final code would look something like:

const conteudo = document.getElementById("conteudo");

conteudo.addEventListener("input", function(event) {
  this.value = this.value.match(/.{1,10}/g).join("\n");
});
<textarea name="conteudo" id="conteudo" rows="6" cols="50"></textarea>
  

The logic has been developed considering that all bar code values will have the same length (10, in this example).

All this processing is done on the client side, but web rule number 1 is never trusting the data received from the user . A very simple example would be for the user to have JavaScript disabled in the browser, which could completely break the application. To avoid this, data validation and processing should be redone on the server side. The Caique's answer already gives a brief introduction to how it could be done in PHP.

    
20.09.2017 / 22:56
0

$('input').on('blur', function(e){
	var txt = e.target.value.split('');
  var aux = "";
  
  var i=0;
  txt.forEach(function(value, idx){
    if(i==9){
      aux += value + "X";
      i = 0;
    }else{
      aux += value;
      i++;
    }
  });
  alert(aux);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><inputtype="text" />
    
20.09.2017 / 21:46
0

If you need to manipulate the value entered in <textarea> after the form is submitted you must do this through PHP , do this on the client side as well as affect user experience , is not secure.

After sending the form to your PHP , use the chunk_split function. That allows you to split the string into pieces.

Assuming your textarea has the name='teste' property follows an example in PHP :

<?php
$teste = $_REQUEST['teste'];

echo chunk_split($teste, 10)
?>

If you really need to run this in client side , follow the example below:

Every 10 char Adds in the string the char specified.

function AlteraTexto(str, n) {
    var ret = [];
    var i;
    var len;

    for(i = 0, len = str.length; i < len; i += n) { //Percorre a string a cada 10 posições
       ret.push(str.substr(i, n))
    }

    return ret
};
var textarea = document.getElementById('teste');

var resultado = AlteraTexto(textarea.value, 10).join('\n');
textarea.value = resultado;
<textarea name="teste" id="teste" rows="6" cols="50">
AAAAAAAAAABBBBBBBBBBEEEEEEEEEE12345678.
</textarea>
    
20.09.2017 / 21:46
0

Import jquery:

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

Set as you want, where X will be, if it is going to be another character and the textarea id.

$(function(){
  var campo = $('#conteudo');
  var posicao = 10;
  var separador = 'X';
  var c = 0;
  String.prototype.replaceAll = function(search, replacement) {
      var target = this;
      return target.split(search).join(replacement);
  };
  campo.keypress(function(e) {
    var code = e.keyCode || e.which;
    if(code == 32) {
       return false;
    }
    c = (campo.val().replaceAll(separador,'').length);
    if(c % posicao == 0 && c != 0){
      campo.val(campo.val() + separador);
    }  
  });
});

Remembering that this type of code does not prevent the user from sending the textarea incorrectly, since it can disable javascript or even change the code using extensions, firebug or some similar tool.

Correct and check the code on the server where the user does not have access.

    
20.09.2017 / 21:56