Insert "X" value after some characters

Asked

Viewed 1,319 times

1

On my form, there’s a textarea and I would like to add, every 10 characters typed, the character X, without submitting the page.

Example:

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

As the user was typing, would insert every 10 characters. In this case, I do not need to mask, but rather add the X to the 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 to count characters and gave a basic change, which only adds +1 every 10 characters typed, value defined in input#tamanho_codbarras.

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

AAAAAAAAAA
BBBBBBBBBB
EEEEEEEEEE
12345678
  • What is your knowledge of Javascript? And could you say what is the purpose of inserting this character in the middle of the text?

  • Eduardo, share with us what you have tried. Edit your question and enter the HTML and the Javascript that used.

  • If you just want to split this text in PHP, I have to say that this solution is bad. Mainly by interfering with the text typed by the user. Imagine you typing a comment here on the site and suddenly it starts to appear X in the middle of your text? Extremely inappropriate. You can split the text every 10 characters with PHP without needing it, but you won’t be able to answer that question.

  • Anderson, let me summarize for you. I have a system in which loads a page only with an input text for the user to read the barcode and Submit is automatic. The user has bad internet, which makes the page load take time. I came up with the idea of leaving a textarea open, as if it were a Powerpoint or excel, and the same read as many codes you want and in the end send, however, the barcode, does not have a character for 'break control', so I posted the question.

  • Okay, but you do realize how uncomfortable this can be, right? If you really want this to be done on the client side, use the character \n instead of X, because it will not generate discomfort and will be visually more pleasant. Then, it will be necessary to analyze how the insertion of the value in the textarea by the bar code reader. Depending on how, not all answer codes will work, as it will depend on the event handled in Javascript. And even if you do this in JS, also remember to treat the information in PHP. Never trust your user data.

  • In the case of X, it was also an example. I’m thinking of using a semicolon. I have two readers on hand and testing. One has auto enter and the other inserts " n" after reading. I’ve done the negotiations in PHP. Really, we can not trust the user, but in this case, we have done everything, but they have a serious problem with the internet, and as I can not lose the client... Even if he type anything, the next screen has a fine-toothed comb that validates the information. I thank you for your help and attention.

Show 1 more comment

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>

That would be about it?

1

Making a compilation of all the information I presented:

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

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

Therefore, 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 line breaking, 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 merge with the code created earlier and define the new field value. The logic will be very simple: whenever there is a change in the field, take the current value, separate it into segments of length equal to 10 (or less) and add the character \n between them, defining the new field value.

As I said, it will be interesting to use the character \n, because this is not visible and generates much better visual comfort, breaking the line with each new bar code.

The addition of the character between the segments can be done by the method join of 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 was developed considering that all bar code values will have the same length (10, in this example).

All this treatment is done on the client side, but the number 1 rule of the web is never trust the data received from the user. A very simple example would be that the user has Javascript disabled in the browser, and can completely break the application. To avoid this, data validation and processing should be redone on the server side. A caique’s answer already gives a brief introduction of how it could be done in PHP.

  • Upvote, some answers like this should be compared to lessons. Regarding the use of Jquery, I just realized that it started to become the comfort zone of many people including me, you kind of made me open my eyes to the unnecessary use of it and how we should gradually get out of our comfort zone to allow us to learn.

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>
<input type="text" />

  • In order to justify my negative vote, I think it is completely unnecessary to use jQuery for such a trivial task and I also see no point in answering a question with a solution that makes no sense. In my view, this is encouraging bad programming practices.

  • Jquery is only being used to speed up development. The rest, I’m using es6. With regard to good practices, there is today a bad concept that their practices are better than mine and vice versa. The fact is that there are several languages and several frameworks precisely so that one can solve the same problem in the same way. Good luck with all that cast.

  • Diego, excuse me, but the bad practices I was referring to was to make the "possible" gambiarra to insert a character X in the middle of a text to use the explode in PHP. That would be gambiarra and that’s what I meant by bad practice. With the author’s new information in the question this proved plausible. What I criticized was to answer any solution without knowing if it would make sense or not. At first it would not, but now it does. I just haven’t removed the negative because it needs an edit on the answer.

  • It’s all right, Anderson. I apologize for the speed, but the fact is that we live under pressure hj on time and that sometimes we feel offended by everyday things. But I got your point.

0

If you need to manipulate the value entered in <textarea> after the form is submitted you must do this through the PHP, do this on the client side in addition to affecting the user experience, it’s not safe.

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

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

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

echo chunk_split($teste, 10)
?>

In case you really need to run it on client side follows an example:

Every 10 char Adds to 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>

  • N knew the chuck_split function, very cool. Problem really is, but it’s the only solution that came into mind with the scenario I have. Back-end we always find a way, now front-end is the problem rs. In case, what I need, adapted with what @Wictor Chaves posted. Thank you for your help and attention.

0

Import the jquery:

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

Set as you wish, position where X will be, if it will be another character and 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 to send 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.

  • @Andersoncarloswoss, man, I use jquery because the code is much simpler, and I don’t know what the goal is for him to need the X, I answered with what he needed.

  • @Wictor Keys, your did exactly what you needed. The objective informed comments above. In this case, I tried to adapt your code, in addition to inserting X, remove the blanks, but I could not. I used a code that I had here. Could you adapt? Thank you very much msm. var $t = Document.getElementById('content'); $t. addeventlistener('Paste', Function(Event); });

  • @Eduardo made a change, now does not allow to have space.

  • @Eduardo if you want to also remove line breaks put this condition here in if (code == 32 || code == 13), 32 is space and 13 and enter.

  • was perfect guy, I added the n tbm, exactly what I needed. So a detail, you know the prq, type a character and already insert the "X" at the beginning? The other inserts correctly, after the defined number of characters, only for the beginning of the content q starts with X.

  • I made the change, now do not put the x in the beginning

Show 1 more comment

Browser other questions tagged

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