0

i have wrote a code of HTML, but the JavaScript function is not called and i have an error message in the console: "myfunction is not a function"

<!DOCTYPE html>
<html>
<head></head>
<body>
    <input type="text" id="mydata"> 
</body>

<script>    
    document.getElementById('mydata').addEventListener("change", myfunction);
    if(typeof mydata.value === 'string' && mydata.value.length === 0){
        console.log('outside function');
    }   
    else{
        function myfunction() {
            console.log('inside function');         
        }
    }               
</script>
</html>
  • 1
    you can't define a function in a if-else statement. You should define it outside and call it anywhere you want doing `myFunction()` – Diego D Apr 05 '22 at 12:34
  • You can define it in a if-else statement. However when your javascript runs, it's going to log 'outside function'. So your code will not be defined until this is false. – Wimanicesir Apr 05 '22 at 12:36
  • @DiegoDeVita Of course you can. Some special handling is even guaranteed in the [specification](//tc39.es/ecma262/#sec-block-level-function-declarations-web-legacy-compatibility-semantics). The global property exists, but is not a function. – Sebastian Simon Apr 05 '22 at 12:36
  • yes ok you can .. I apologize I trascended the OP issue. Yes you can define a function in any scope, what I meant is that it doesn't make sense the way you did. The answer is actually really easy to craft but it's so much out of my understanding any guess that code makes in the condition. Otherwise it would be as easy as just binding that even handler inside a document.ready event and correctly deal with the function invocation in the else branch. – Diego D Apr 05 '22 at 12:37
  • Related: everything that comes up while searching [`"block-level-function-declarations-web-legacy-compatibility-semantics"`](/search?q=url%3A%22block-level-function-declarations-web-legacy-compatibility-semantics%22) (part of the spec link) here. – Sebastian Simon Apr 05 '22 at 12:40
  • By the way, what are you trying to accomplish with your code? It looks non-sensical and relies on [another legacy behavior](/q/3434278/4642212). The `value` getter always returns a string; no need to check its type. Did you mean `document.getElementById("mydata").addEventListener("change", ({ target: { value } }) => { if(value.length === 0){ console.log("Empty"); } else{ console.log("Not empty"); } });`? – Sebastian Simon Apr 05 '22 at 12:45

0 Answers0