简体   繁体   中英

Code snippet works but not in my html file

So basically, I've been looking at different questions and found a code snippet that worked perfectly in the snippet run. But when I copied it into my HTML file, it doesn't work.

My apologies if I sound like an idiot I'm a bit of a biggener.

I've checked other questions including jQuery snippet doesn't work and Code works in Codepen, but not with my desktop files

But still couldn't seem to find a solution.

My code is as follows.

 <script> $(document).ready(function() { $('#newsletter').on('click', '#newsletterButtonSubmit', function() { var inputVal = $(this).parent('div').find('#newsletterInputEmail').val(); console.log(inputVal); }); }); </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id="newsletter"> <div class="newsletter"> <h6 class="headerDIV">SUBSCRIBE TO OUR NEWSLETTER</h6> <input id="newsletterInputEmail" class="input-email" type="email" placeholder="Enter your email here"> <button id="newsletterButtonSubmit" width="100px" class="w3-button w3-round-xlarge w3-grey">Submit</button> <p><label id="newsletterEmailMSG" class="textFillField">This field is mandatory</label></p> <p><input id="newsletterCheckbox" class="w3-check" type="checkbox"><label class="textRights">I have read and accepted the general terms and conditions*</label></p> <p><label id="newsletterCheckboxMSG" class="textFillField">This field is mandatory</label></p> <label class="textRights2">See our <a href="politics/privacy/politica_de_privacidade_pt.pdf" target="_blank" style="text-decoration: underline;">Privacy Notice</a> for more information.</label> </div> </div>

When I open the file in my browser, the script part doesn't work at all. It does nothing.

Any help is greatly appreciated:! :)

Next to the order of loading, you have forgot the thing that the variable $ is not defined

var $ = jQuery.noConflict();

Full example:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

  <script>
    var $ = jQuery.noConflict();
    $(document).ready(function() {
      $('#newsletter').on('click', '#newsletterButtonSubmit', function() {
        var inputVal = $(this).parent('div').find('#newsletterInputEmail').val();
        console.log(inputVal);
      });
    });
  </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM