简体   繁体   中英

How to execute if statement after page has been loaded?

see it in action here: http://jsbin.com/relamiqeru/1/

I am trying to make it so that if a user enters "idh4" into the coupon code field, my "booyah" div gets filled with that html provided.

The issue I feel, is that the javascript is only executed when the page is loaded, so even if idh4 is entered into the field, its not checking it anymore. Perhaps an if statement is not the right thing to use in this case?

At request, here is the jsbin code:

  <div id="booyah"></div>
<form action="" method="POST">
        Coupon Code?<input id="couponcode" type="text" name="coupon code" value="idh4"><br>
        <input type="submit">
    </form>

$("#couponcode").change(function(){
if ($("#couponcode").val() === 'idh4') {
      console.log('it got called');
      $( "#booyah" ).html("<p>That code gets you free snappie stickers!</p>");
  }

  });

I'm not sure this is what you want, but you can take a look at it anyway :

$(document).ready(function(){
   $("#booyahInput").on('keyup', function(){
      if ($(this).val() == 'idh4') {
         console.log('it got called');
         $( "#booyah" ).html("<p>That code gets you free snappie stickers!</p>");
      }
    });
});

http://jsfiddle.net/rwxygptf/

Here problem is you have used change event on textbox:

$("#couponcode").change

On textbox change gets fired on losing focus. So after entering coupon user has to go off the field.

Instead try input , keyup , keypress events for immediate response.

$("#couponcode").on('input', function(){
    //
});

If you want it on submit, you have to add a function to fire on submit, if you want it to fire on text changing in the field - You need to listen to events. Understanding event listeners is key to understanding javascript.

Here are 2 references: Submit:

http://www.javascript-coder.com/html-form/html-form-tutorial-p1.phtml

Listener:

jQuery Listen For All Text Input Changes

The problem you are having, is when the form is submitted the page is reloading. To do this properly you will need to submit the form through AJAX and prevent a page refresh. But with the code you provided it's not clear if you're doing that.

JSFiddle

$("#myform").on("submit", function(e) {
    e.preventDefault();
    if ($("#couponcode").val() === 'idh4') {
        console.log('it got called');
        $("#booyah").html("<p>That code gets you free snappie stickers!</p>");
    }
});

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