简体   繁体   中英

jQuery keypress event function not working

I am trying to add a keypress event into my dynamically created input element.

The keypress event doesn't work when I execute the code. Where have I gone wrong?

 var input = document.createElement("input"); input.className = "installments"; $(document).ready(function() { $('.installments').keypress(function() { if (+$('.installments').val() <= 0 || +$('.installments').val() > 12) alert("Installments should be within 1-12 months range"); }); }); document.querySelector('#testElement').appendChild(input);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="testElement"></div>

The problem is primarily that you can't get the value of an element set, which is what $('.installments') returns. See https://api.jquery.com/class-selector . You'd have to refine the selector or take the first element by index, or use this as I've done here.

Then, you're using the keypress event, which fires before a value has been set. I've changed it to keyup .

I'd also suggest setting your input to type number for better input validation, though a select element with specific options values may actually be the best UX approach.

Then, alerts are a terrible UX mechanism. They require the user to take useless action, and they're not stylable. Look to HTML validation or custom inline messaging instead.

Finally, let and const are more modern ways to store values. They have better safety checks and more intuitive scoping.

 let input = document.createElement("input"); input.type = 'number'; input.className = "installments"; $(function() { // shorthand for document.ready $('.installments').keyup(function() { const inputVal = parseInt($(this).val()); console.log(inputVal); if (inputVal <= 0 || inputVal > 12) console.log("Installments should be within 1-12 months range"); }); }); document.querySelector('#testElement').appendChild(input);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="testElement"></div>

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