Search code examples
javascriptdom-events

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?


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.