Send what is being typed from one input to another in real time

Asked

Viewed 266 times

2

Hey, you guys!
I don’t understand Jquery or javascript, only PHP.
I am struggling to create an INPUT 1, which in real time, sends what is being typed to an INPUT 2, without spaces or special characters.
Currently I treat it in PHP.
Example:

<form>
  <label>Nome</label>
  <input type="text" name="INPUT1">

  <!-- Recebe os dados do INPUT 1 sem espaços e caracteres especiais-->
  <label>Url</label>
  https://meusite.com.br/<input type="text" name="INPUT2">
</form>

I hope I’ve been clear and I’m waiting for help from the community.

  • "without spaces or special characters" - input1 gets things you want to filter?

3 answers

5


Speaking in a simple way to understand, you can do so.

function trim(str) {
   return str.replace(/[^a-zA-Z0-9]/g, '' )
}

let input = document.getElementById('um')
let input2 = document.getElementById('dois')

input.onkeyup = function(){ 
  input2.value = trim(input.value)
}
<input type="text" id="um" placeholder="Input 1">

<input tyoe="text" id="dois" placeholder="Input 2">

  • 1

    That’s right, but the second input cannot go (allow) special characters or spaces.

  • @Márcioteixeira I edited the answer, I hope it helps

4

You can use regex to swap special characters or spaces for nothing.

let input = document.getElementById('um')
let input2 = document.getElementById('dois')

input.onkeyup = function(){
  let valor = input.value.replace(/[^\w\s]|\s/gi, '');
  input2.value = valor
}
<input type="text" id="um" placeholder="Input 1">

<input type="text" id="dois" placeholder="Input 2">

4

You can do as follows, using regex to filter the special characters

$('#input1').on('change keyup', function () {
  $('#input2').val($(this).val().replace(/[^a-zA-Z0-9]/g, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1" type="text"/>
<input id="input2" type="text"/>

Browser other questions tagged

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