2

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);
})
});

3 Answers 3

2

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);
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

0

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);
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.