Home > Software design >  jQuery input element with id selection using id selector
jQuery input element with id selection using id selector

Time:12-29

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 >
    <div >
        <input id="newsletter-subscription-email"  type="email" title="Subscribe to our newsletter!" placeholder="Email address">
        <div >
            <button id="newsletter-subscribe"  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?

CodePudding user response:

I faced the same thing with you months ago. At last, I found that there were two controls with the same ID, jquery always choose the first one with the ID

your code is perfect, please check is there are more than one input with that ID attr

CodePudding user response:

Probably the $()ready(function(){ and also a missing }); in the js.

$(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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div >
    <div >
        <input id="newsletter-subscription-email"  type="email" title="Subscribe to our newsletter!" placeholder="Email address">
        <div >
            <button id="newsletter-subscribe"  type="submit" role="button">Subscribe</button>
        </div>
    </div>  
</div>

  • Related