How to avoid double spaces in html input?

3

I want to avoid those annoying double spaces in some inputs, do you have any idea how I can do it? I do not think I have a problem with doing it completely on the client's side.

Here is an example of one of my input:

 <div class="form-group">
      <label for="cliente">Cliente</label>
      <input type="text" name="cliente" class="form-control" id="cliente" placeholder="cliente">
 </div>
    
asked by Daniel Treviño 10.11.2017 в 21:04
source

1 answer

2

The solution would be verifying the last written key, if the last key is space we would have to deny the writing to the second space with event.preventDefault();

document.getElementById("text").addEventListener("keydown", teclear);

var flag = false;
var teclaAnterior = "";

function teclear(event) {
  teclaAnterior = teclaAnterior + " " + event.keyCode;
  var arregloTA = teclaAnterior.split(" ");
  if (event.keyCode == 32 && arregloTA[arregloTA.length - 2] == 32) {
    event.preventDefault();
  }
}
<input type="text" id="text"></input>
    
answered by 11.11.2017 / 05:08
source