Home > Blockchain >  getting undefined when trying to get value from textbox using JQuery
getting undefined when trying to get value from textbox using JQuery

Time:07-03

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 ><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.

CodePudding user response:

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/

CodePudding user response:

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 ><button onclick="foo()">Submit</button></div>
  </div>

  • Related