Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

345
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda