Changing the function name to something else, like require()
will work:
function require(inputtx) {
console.log('Success');
}
<input type="text" name="nbreAdultes" id="nbreAdultes" autofocus onblur="return require(document.getElementById('nbreAdultes'));" />
When you use required
as an identifier, it's interpreted as the required
property of the element instead of the name of your function:
<input type="text" onblur="console.log(required)" /> <!-- logs "false" -->
<input type="text" onblur="console.log(required)" required /> <!-- logs "true" -->
The reason for this is that event handlers defined as attributes execute in a different scope than normal functions. To resolve a variable x
defined in a normal function, the runtime will first look for a local property named x
, and if that cannot be found, it will try to find a global property of the same name.
For event handler content attributes in HTML, the scope chain is different. After trying to resolve the identifier locally (in the event handler itself), JavaScript will try to resolve it as a property of the element on which the event handler is defined. If it can't be resolved there, it will continue up the hierarchy until arriving at the global Window
object.
So, in summary, the behavior you're witnessing occurs because your required()
function is defined higher up the scope chain than the element's required
property.