Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why `return` is used in javascript event function

Html: <input type="text" onkeypress="return isNumberKey(evt)" />

JavaScript:

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;

    if (charCode != 46 && charCode > 31
        && (charCode < 48 || charCode > 57))
        return false;
    

    return true;
}

My Question Why there is return used in onKeypress event.

Code Explaination Basically after appling this function, input feild only accepts number. i am surprised, how input feild value is forced to received only number ? AsisNumberKey() function only return ture / false not the value?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The return statement in the onkeypress event handler function serves a specific purpose. In JavaScript, when an event handler function returns false, it prevents the default behavior of the event from occurring. Conversely, when it returns true, the default behavior is allowed to proceed.

In the case of the isNumberKey function that you provided, it’s used as an event handler for the keypress event on an input field. This function is designed to control which characters are allowed to be entered into the input field. If the function returns true, it allows the character input (key press) to be displayed in the input field; if it returns false, it prevents the character input from being displayed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading