I have a HTML with input forms and button:
<input id="nameField" type="text">
<input id="submitBtn" type="button" value="Submit">
And script:
$(function() {
var name = $('#nameField').val();
var data = {
name: name
}
$('#submitBtn').click(function() {
alert(data.name);
});
});
Enter text into the field and click button. But the alert is the empty and there are no errors in the console.
That’s because you initialize
dataas soon as the document is ready, long before the user enters the text.You can do that :