I am using JQuery 3.6 and I’m trying to create a simple email registration snippet on a page.
I am surprised that when I type an email in the input, and click the button, the alert box shows a blank. I get the same result when I use Code Inspector. The element is identified and selected correctly, but for some reason, I can’t seem to extract the email value entered in the input box.
Here is my markup and minimal Javascript:
<div class="g-mb-30">
<div class="input-group border-0 rounded">
<input id="newsletter-subscription-email" class="form-control border-0 g-pa-12" type="email" title="Subscribe to our newsletter!" placeholder="Email address">
<div class="input-group-append p-0">
<button id="newsletter-subscribe" class="btn btn-primary" type="submit" role="button">Subscribe</button>
</div>
</div>
</div>
<script type="text/javascript">
function isValidEmail(some_email){
/* impl detail */
}
$()ready(function(){
$('#newsletter-subscribe').on('click', function(e){
let email = $('#newsletter-subscription-email').val().trim().toLowerCase();
alert(email); // displays blank if even I type an email address
if (email.length && isValidEmail(email)) {
e.preventDefault();
// some logic ...
}
}
});
</script>
Why is the address not being correctly retrieved – since the selector CSS is correct – and how do I fix this to correctly retrieve the entered email?