Pick user input value with jQuery

Asked

Viewed 2,717 times

0

Hello! Here’s the thing, in my form, I’m trying to get the value typed by the user in the input way below:

// jQuery
function teste() {
var nome = $("#nome").val();
alert(nome); 
}

// HTML
<form method="post" action="#">
   <div class="field half first">
        <label for="nome">Nome</label>
        <input type="text" name="nome" id="nome">
   </div>
   <div class="field half">
        <label for="sobrenome">Sobrenome</label>
        <input type="text" name="sobrenome" id="sobrenome">
   </div></form>
<button onClick="teste()">Teste</button>

But it returns no value, generates a blank Alert() regardless of what the user has typed. Does anyone know what it might be? If useful, I am using Codeigniter

  • This can happen if you have more than one element with the same ID.

  • I checked that possibility, but there’s only one element with the same ID

2 answers

1

You can do so that brings the value of the field without using the Jquery:

function teste() {
   var nome = document.getElementById("nome").value
   alert(nome); 
}
  • I tried, but it also returned empty. It seems that it only returns the value of the attribute value="" if it is inserted, ai as not inserted, empty back

0

Use jquery, instead of this onlick put an id <button id="teste">Teste</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="#">
   <div class="field half first">
        <label for="nome">Nome</label>
        <input type="text" name="nome" id="nome">
   </div>
   <div class="field half">
        <label for="sobrenome">Sobrenome</label>
        <input type="text" name="sobrenome" id="sobrenome">
   </div></form>
<button id="teste">Teste</button>

<script type="text/javascript">
    $("#teste").click(function() {
    var nome = $("#nome").val();
    alert(nome); 
    });
 </script>
  • Nor will it, it seems that it can only bring the value of the attribute value="" and if it is not, ai returns empty

  • if the value is empty you need to validate with an if($("#name").val() == null) do something... but your problem was the button that was not working right?

Browser other questions tagged

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