Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

340
Visualizações
getting undefined when trying to get value from textbox using JQuery

I am getting undefined whenever I try to get a variable from a textbox

let fname = $("#firstName").val();
let lname = $("#lastName").val();
let fullname = fname + " " + lname;

function foo() {
    alert(fullname);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <div>
  <div class = "person">First name:<input type = "text" id = "firstName"></div>
  <div class = "person">Last name:<input type = "text" id = "lastName"></div>
  <div class="person"><button onclick="foo()">Submit</button></div>
  </div>

I have tried to remove the "#" from the fname and lname variables, but then it prints "undefined"

I am confused on why this is happening.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Variables declared by let have their scope in the block for which they are declared, as well as in any contained sub-blocks. In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function.

So use either var

var fname = $("#firstName").val();
var lname = $("#lastName").val();
var fullname = fname + " " + lname;

function foo() {
    alert(fname);
    alert(fullname);
}

For scoping of let see e.g. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
You need the # in jquery to access the id, see for example https://learn.jquery.com/using-jquery-core/selecting-elements/

about 4 years ago · Juan Pablo Isaza Relatório

0

Try This

function foo() {
let fname = $("#firstName").val();
let lname = $("#lastName").val();
let fullname = fname + " " + lname;

    alert(fullname);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <div>
  <div class = "person">First name:<input type = "text" id = "firstName"></div>
  <div class = "person">Last name:<input type = "text" id = "lastName"></div>
  <div class="person"><button onclick="foo()">Submit</button></div>
  </div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda