Separate each two values by commas in javascript

1

I am trying to implement a system that when the user enters numeric data in a textarea, these will be separated by a comma every two values. As an example, another part of the program consists of pressing a button to generate a random number between -10 and 99 and this number shows them in a textArea. This I get well with this code:

function tipoRadio()
{
var medidas = elementoID("medidas");//capturo elemento

if (this.id === "medidas_manual")//si el elemento tiene este id 
{
    medidas.value = "";//le vacio
    medidas.disabled = "";//le habilito para poder escribir en el

}

if (this.id === "medidas_aleatorio")//si tenemos este id
{
    var aleatorios = generarValoresAleatorios();//obtengo array aleatorios
    var ale = "";
    for (var i = 0; i < aleatorios.length; i++) {
        ale += aleatorios[i] + ", ";//Los voy añadiendo a una variable con 
                                      comas en medio
    }
    medidas.value = ale;//muestro la variable
    medidas.disabled = "false";     
  }
 }

function generarValoresAleatorios()//Funciona que me genera el array 
                                    aleatorios
{
var arrayAleatorios = new Array();
for (var i = 0; i < 30; i++) {
    arrayAleatorios.push(aleatoriosEntreMinimoMaximo(-10, 99));
}
return arrayAleatorios;

}

This result I want to get but the user will enter the data manually. Only number in format two digits 01, 44, 08 or is also valid -9, -6 for negative numbers. The maximum number of digits is two. The user is not obliged to write the commas .... Summing up, the user enters:

  • 00 ------------ well
  • 80 ------------ good
  • -5 ------------ good
  • 06 ------------ well
  • 6 ------------ badly missing another digit
  • 7- ------------ bad the least can not go behind just in front (negative number)

I do not know if I explain. I'm editing the question as I go polishing the problem thanks to the comments. Greetings

    
asked by Carlos Rayón Álvarez 19.03.2018 в 13:01
source

3 answers

3

and everyone has contributed their bit to the problem, let's see if my help is any good.

First, I define a format function that basically analyzes the content of the textarea, converts it into an array of numeric values and then fills the textarea with those values separated by comma + space.

var element=document.querySelector('#numeros'),
    contenido=element.value;
    contenido_arr=contenido.replace(/,/g,' ').trim().split(/\s+/);
    element.value=contenido_arr.join(', ');

Second, I have another function that runs every time a character is entered into textarea. If it is not numeric, neither comma nor space, it does not insert the character.

If it is a space, check if there is an accumulated space, so that writing número + espacio + número + espacio the first space marks a flag: "there is a space waiting for formatting" and the second space says: "the flag is marked, we apply formatting " The idea of this is that you can write número + espacio + número without that space triggering formatting preventing you from writing the second number. This has another edge case. If you want to insert a number in the middle of the ones you already have, the function needs to tolerate that you insert a space before triggering the formatting.

Third, if the textarea loses focus (event onblur ) the formatting is triggered.

The solution is not perfect, but it roughly meets your intention:

var spacepending=false;
var format = function() {
  var element=document.querySelector('#numeros'),
      contenido=element.value;
      contenido_arr=contenido.replace(/,/g,' ').trim().split(/\s+/);
      element.value=contenido_arr.join(', ');
};
var checkKey = function(event) {
  
  var keyName = event.key;
  if(keyName===',') {
    //no hago naga
  } else if (keyName === ' ') {
    if(spacepending) { // si ya se insertó un espacio, ejecuto el formateo
      format()
      spacepending=false;
    } else { // si no, almaceno que hay un espacio pendiente
      spacepending=true;
    }
  } else if(isNaN(keyName)) {
    event.preventDefault();
    return false;
  }
  
  
};
#numeros {
width: 100%;
height: 100px;
background:#f7f7f7;
}
<textarea id="numeros" onkeypress="checkKey(event, this)" onblur="format()" ></textarea>
    
answered by 19.03.2018 / 17:10
source
5

I have created a function that more or less solves your problems, it could be separated into 3 parts, the main one collects the data of the key press event and if it has "," it separates it into an array by these ","

The second part would be a for to traverse the chain and every 2 values put a "," in the middle

The third part would be the reorganization of values and insert them in the field

$("#target").keypress(function (e) {
//1
        var value = $("#target").val() + String.fromCharCode(e.which);
        var splits = value.split(",");

        if (splits.length > 1) {
            value = splits[splits.length-1];
        }

//2
        var finalValue = "";

        for (var i = 0; i < value.length; i++) {
            if (i % 2 == 0 && i != 0) {
                finalValue = finalValue + ',';
            }
            finalValue = finalValue + value.charAt(i);
        }
    //3
        if (splits.length > 1) {
            splits.splice(splits.length-1);
            var concat = splits.concat(finalValue);
            finalValue = concat.join()
        }
        $("#target").val(finalValue.substring(0, finalValue.length - 1));
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="target" rows="4" cols="50"></textarea>
    
answered by 19.03.2018 в 15:59
2

Using the divide and conquer strategy, divide your problem into two parts:

  • Imagine that you have a single entry (a two-digit value) and you want to check if it is valid. You can create a function that takes that entry and validates it, for example esValorValido(valor);
  • Using this function in an iterative way, you can validate all the entries, so what you have left is to divide the text of textarea in the entries:

let valorDelTextArea='55, 06,77,-1,';

let valores=obtenerValores(valorDelTextArea);

function obtenerValores(texto) {
  if (!texto) return []; // ningún valor en una cadena vacía
  
  let valores=texto.split(',');
  
  return valores.map(v=> v? v.trim() : undefined );
  
}


console.log(valores);

And now you can create a loop that tells you if each of those values is correct or not.

    
answered by 19.03.2018 в 15:49