Get value entered by the user in the input with jQuery

0

Hello! It's the following, in my form, I'm trying to get the value entered by the user in the input as follows:

// 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 does not return any value, it generates a blank alert () regardless of what the user has typed. Does anyone know what can it be? If it's useful, I'm using Codeigniter

    
asked by anonymous 06.03.2018 / 02:49

2 answers

1

You can do this by bringing the JQuery field value:

function teste() {
   var nome = document.getElementById("nome").value
   alert(nome); 
}
    
06.03.2018 / 14:06
0

Use jquery, instead of that 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><formmethod="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>
    
06.03.2018 / 14:34