Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On keypress does not fire on the first key press

I have this method:

$(".txtB").on("keypress", function(event) {
    console.log($(this).val());
    if (...)
        event.preventDefault();
});

But it works only after the second key pressed not for the first one. After that is triggered on every key press. Anyone have an idea what could be?

Thanks.

Later edit: It might be related to the way i use the function?

in HTML: onkeyup = "caseValuePercentageTwoDecimalRestriction()"

in JS:

function caseValuePercentageTwoDecimalRestriction() {
    $(".caseValuePrecentageRestriction").on("keypress", function (event) {
        ...

??

like image 433
Jake Manet Avatar asked Sep 15 '25 06:09

Jake Manet


2 Answers

$(".txtB").keyup(function (event) {
     console.log($(this).val());
});

To answer your question, Keypress event happens before the input change. But Keyup happens after the change. That's the only difference.

like image 153
Raja Sekar Avatar answered Sep 17 '25 20:09

Raja Sekar


The error is calling caseValuePercentageTwoDecimalRestriction on keyup event which is fired after keypress event.

keyup is called when you release the key while keypress is called when you press the key.

You should bind you keypress event handler on a document.ready event like this:

$(document).ready(function() {
    $(".caseValuePrecentageRestriction").on("keypress", function (event) {
        // do whatever you need
    });
});
like image 26
ADreNaLiNe-DJ Avatar answered Sep 17 '25 18:09

ADreNaLiNe-DJ