Javascript var function inside

I am new to javascript and I want to understand why this is not working:

var firstName = $("#firstName").val();

$("#account").on('submit', function() {
     console.log(firstName); // Empty value
});

jsfiddle: FIDDLE

+4
source share
7 answers

You get the initial value of the input and save it in a string variable. Instead, save the jQuery object reference in a variable and get the value whenever you want.

var firstName = $("#firstName");

$("#account").on('submit', function() {
  console.log(firstName.val());
});

var firstName = $("#firstName");

$("#account").on('submit', function() {
  console.log(firstName.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="account" method="post">
  <input type="text" id="firstName">
  <input type="submit">
</form>
Run codeHide result
+3
source

, firstname firstName. , , . , :

$("#account").on('submit', function() {
     var firstName = $("#firstName").val();   // get current value
     console.log(firstName); 
});
+4

.

var firstNameDefault = $("#firstName");

$("#account").on('submit', function() {
    var firstNameAfterClick = $("#firstName");
    console.log(firstName.val()); // Empty value
    console.log(firstNameAfterClick.val()); // Should display value of #firstName after form is submitted
});
+1
var firstName = $("#firstName").val(); // move this line from here to inside the function

$("#account").on('submit', function() {
     var firstName = $("#firstName").val();
     console.log(firstName); // Empty value
});
0

, , .

$("#account").on('submit', function() {
     var firstName = $("#firstName").val();
     console.log(firstName); // non-empty value
});
0

. , username $("#firstName")

, :

var firstName = $("#firstName").val(); // this line says that get the value of #firstName

, #firstName , , , , . - , .

$("#account").on('submit', function() {
     console.log(firstName); // Empty value
});

, #account , firstName . , , #firstName. #firstName, . , .

0

I assume that you have the default value in #firstName, which you want to see by default, without any changes to the browser console. The page refreshes to submit the form, so you cannot see the value of the console. so just add another line return false;to see it in the console.

<script>
    var firstName = $("#firstName").val();

    $("#account").on('submit', function() {
        console.log(firstName); 
        return false;
    });
</script>

*** and do not forget to delete it return false;after completing your debugging, otherwise the form will not be sent to the server.

0
source

All Articles