Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

339
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!