Reputation: 251
I have a simple HTML form and try to get the value for email and password from it with jQuery. In result I always get empty string. Can someone please tell me what I have to change
HTML form:
<form>
<label for="email">Email</label>
<input type="email" id="email">
<label for="password">Password</label>
<input type="text" id="password">
<button id="button">Submit</button>
</form>
jQuery code :
$(function() {
var x = $("#email").val();
var y = $("#password").val();
$('#button').click(function() {
alert(x);
alert(y);
})
});
Upvotes: 2
Views: 1397
Reputation:
I would suggest you use the on("click")...
instead of .("click")
More sore if your values are dynamic. .("click")
function may fail to fire the second time.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).on("click", "#button", function(e) {
e.preventDefault();
var x = $("#email").val();
var y = $("#password").val();
alert(x);
alert(y);
});
</script>
<form>
<label for="email">Email</label>
<input type="email" id="email">
<label for="password">Password</label>
<input type="text" id="password">
<button id="button">Submit</button>
</form>
Upvotes: 1
Reputation: 21
You could get the values inside the click handler. The problem is that you are trying to get the values once the document is ready, in that moment they are empty.
You can add a listener for the submit event of the form and get the values on submit.
For example:
$('form').on('submit', function() {
var x = $("#email").val();
var y = $("#password").val();
alert(x + ' | ' + y);
})
Upvotes: 0
Reputation: 5146
The problem is that the part where you get the value of the email and password fields is only run once. You want to run it again on every click to get the current value.
$(function() {
$('#button').click(function() {
var x = $("#email").val();
var y = $("#password").val();
alert(x);
alert(y);
});
});
Upvotes: 2