After a submit button is clicked, outside 'click' event I use 'alert' to display the variable which is assigned a value from an input text. Why was a blank value returned? Then, I tried to create a function containing an 'alert' for that variable, and I used this function in 'click' event that resulted in value of textbox is shown. Why does this happen? How are two operation different? HTML:
<form id="myForm">Your name:
<input type="text" id="nametxt" />
<input type="button" value="submit" id="submit" />
</form>
jQuery: (First experiment)
var name = "";
$("#submit").click(function(){
name = $("#nametxt").val();
});
alert(name); ==============> Unexpected result: blank value
jQuery: (Second experiment)
var name = "";
var makeSentence = function() {
return name + " is nice!";
}
var myFunc = function() {
alert(makeSentence());
}
$( "#submit" ).click(function() {
name = $('#nametxt').val();
myFunc(); ==========================> Expected result: "yourname is nice!" is alerted.
});
Why do experiment 2 display name's value but experiment 1 don't?