-1

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?

Toha
  • 5
  • 3
  • So that the caller can get a `true` / `false` response. – Keith Aug 03 '23 at 11:16
  • _"i am surprised, how input feild value is forced to received only number"_ - well exactly _by_ returning false. Which means, "do not perform the default action this event would have" - and that default action for a keypress on an input element, would be that the character corresponding to the key gets added to the field's value ... – CBroe Aug 03 '23 at 11:18
  • The return value of the event handler is used to determine if the default browser behavior should take place or not. – Jean-Baptiste Yunès Aug 03 '23 at 11:21
  • Not sure what your using to learn JS, but it might be best to find something more modern, `onkeypress` is actually deprecated event, `Be aware that this feature may cease to work at any time.` -> https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event – Keith Aug 03 '23 at 11:24
  • @CBroe thanks . your explanation is very clear, simple, informative. – Toha Aug 03 '23 at 11:26
  • @Keith would you guys please suggest me a good resource to learn javascript? – Toha Aug 03 '23 at 11:29
  • uTube is a good resource, but just make sure you filter out old articles, maybe restrict to uploads within the past 3 years. As well as `onkeypress` been deprecated, even the HTML inline event handlers are suggested to leave alone, and use `addEventListener` instead. Avoid articles using jQuery, it was a good in it's day, but not really required these days. – Keith Aug 03 '23 at 11:37
  • Oh and finally, a good resource that can't be left out is MDN, https://developer.mozilla.org/en-US/ – Keith Aug 03 '23 at 11:39

1 Answers1

0

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.