Problem to get input value with javascript

Asked

Viewed 1,021 times

2

I’m taking the value of input via JS and sending via GET to another page. The problem is that when I type space in the input, I can’t get what I wrote after space.

If I type for example: Ana Maria the JS only takes the Ana.

THE HTML:

<input type="text" id="nome" onkeyup="pegaNome()">
<div id="aqui"></div>

The JS function:

 function pegaNome(){

    var campo=document.getElementById('nome').value;
    $(document).ready(function(){
    $('#aqui').append(campo);

});
  • 1

    Retire $(document).ready(function(){ and add $('#aqui').html(''); before the append. You are not using $(Document). ready(Function(){ in the correct way.

2 answers

4

Suggestion or make on Javascript pure or Jquery, makes it easier to understand the logic. (In your example there was mixture of Jquery with pure Javascript)

Below is your example working in Jquery.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#nome").keypress(function(){
        var valor = $("#nome").val();
        $("#aqui").text(valor);
    });
});
</script>
</head>
<body>

<input type="text" id="nome">
<div id="aqui"></div>

</body>
</html>

In pure javascript:

 <html>
    <head>
    <script>
    function peganome(valor) {
      document.getElementById("aqui").innerHTML = valor;
    }
    </script>
    </head>
    <body>
    <input type="text" id="nome" onkeyup="peganome(this.value);">
    <div id="aqui"></div>
    </body>
    </html>

In Angularjs (without jquery or any other plugin)

<html ng-app>
  <head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
  </head>
  <body>
    <div>
      <label>Nome:</label>
      <input type="text" ng-model="nome">
      <hr>
      <h1>Olá {{nome}}!</h1>
    </div>
  </body>
</html>

NOTE: In Angularjs is the easiest basically is an ng-model="name" and then to display is {{name}}, but use Angularjs only for That’s like having a Ferrari to go to just the bakery.

2


You can do it like this:

function pegaNome(valor) {
  document.getElementById("aqui").innerHTML = valor;
}
<input type="text" id="nome" onkeyup="pegaNome(this.value);">
<div id="aqui"></div>

Browser other questions tagged

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