Read content input [closed]

0

I'm trying to read the text inside a input field, but it's not working, what could be wrong?

My code:

<input type="text" id=-"campo-de-busca" onKeyPress="teclaPressionada()" placeholder="Nome">

function teclaPressionada()
{
    var texto = $("#campo-de-busca").val();
    alert(texto);
}
    
asked by anonymous 07.08.2017 / 14:50

3 answers

3

You can use the events named KeyBoard Events that are these:

  • KEYDOWN
  

The key event is sent to an element when the user presses a key on the keyboard. If the key is held down, the event is sent whenever the operating system repeats the key.

KEYDOWN EVENT JQUERY

  • KEYPRESS
  

The keypress event is sent to an element when the browser registers the keyboard input.

KEYPRESS EVENT JQUERY

  • KEYUP
  

The key event is sent to an element when the user releases a key on the keyboard.    KEYUP EVENT JQUERY

Below you can see an example using jQuery and the above events.

You can change the event to keypress or keydown

$(function(){
  $('#teste').on('keyup',function(){
    console.log(this.value);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="teste">
    
07.08.2017 / 15:18
1

has - in its id field

<input type="text" id="campo-de-busca" onKeyPress="teclaPressionada()" placeholder="Nome">

But what would you that would not be onclick instead of onkeypress?

    
07.08.2017 / 15:08
0

The solution to your problems goes through

  • A correction of the value of the id attribute of your HTML input from -"campo-de-busca" to "campo-de-busca" . Note that you have a hyphen just after the equal sign.
  • Change event onKeyPress to onkeyup so that the function is triggered as soon as the key is pressed.

function teclaPressionada()
{
    var texto = $("#campo-de-busca").val();
    console.log(texto);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="campo-de-busca" onkeyup="teclaPressionada()" placeholder="Nome">
  

For more details on the differences between OnKeyUp, OnKeyDown and OnKeyPress, see this Post

With jquery

var userTyped = '';
$(document).ready(function(){
$("#campo-de-busca").keypress(function(e){
userTyped += String.fromCharCode(e.which);
console.log(userTyped);
});
$( "#campo-de-busca" ).focus();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="campo-de-busca" placeholder="Nome">
    
07.08.2017 / 15:40