I have this code, and a very common error that I have is that we very much control the scope
between HTML
and Javascript
, by that I mean that many times when I call a function directly from the HTML and that function is in a separate js file, it always tells me that the function is not defined , like here:
As you can see by clicking on the text inputs, the function is not defined in the console.
The function that says not to be defined is the checkRealTime
, that function is added by onblur
to all inputs
of the document (I think because in addition the onblur
does not work correctly at the first click , then there must be more errors still ...)
How to fix this, and why does it happen?
/* Independent functions */
window.addEventListener('DOMContentLoaded',functions); /* Waiting for DOM Load */
function functions(){
var getLabels = document.getElementsByTagName('label'),j=0,lmax=getLabels.length;
for(;j<lmax;j++) { getLabels[j].style.fontFamily = 'Monospace'; }
validateInputs();
function checkRealTime(id){
console.log(id);
}
}
function validateInputs(){
var pattern = /[0-9]/;
var inputs = document.getElementsByTagName('INPUT');
for(let i = 0; i<inputs.length;i++) {
inputs[i].setAttribute('onblur','checkRealTime('+inputs[i].id+')');
}
}
<!DOCTYPE html>
<html>
<head>
<title>zero to hero ?</title>
<meta charset='utf-8'>
<script src="functions.js"></script>
<script src="igenerator.js"></script>
</head>
<!-- I define the default css values !-->
<style>
body { color: gray; margin: 0;}
.title { font-family: monospace; color: black; font-size: 25px; margin-left: 35vw;}
.ms { font-family: monospace;}
</style>
<body>
<b class="title">Javascript Input generator(and can be deleted)</b>
<hr></hr>
<label for="inputgen"> Number of inputs to be generated: </label>
<input type="text" placeholder="to add" id='inputgen'> <input type="button" value="Generate" id='b-generate'>
<label for="idel"> Number of inputs to be deleted: </label>
<input type="text" placeholder="to delete" id="idel"> <input type="button" value="Delete" id="b-delete">
<hr></hr>
</body>
</html>