Search code examples
javascripthtmltextboxonblur

Error in html file with Javascript onBlur event


I'm reading a tutorial of Javascript, I'm making a html file with a javascript function with a box, the fact is that the alert does not show what goes into the text field, what am I doing wrong ?, this is my code. I'm not entirely clear, how it handles the event onBlur, someone explain more about it? as in the tutorial the only explanation they give is "Losing the focus control," I don't know what they mean by the word focus, or how it is handled the text box, without enter botton.

<html>
    <head>
        <script>
            function show ()
            {
            var age= parseInt (cage.value);
                if (age<=18)
            alert("access denied");
                else
            alert("Welcome");
            }
        </script>
        <title> New Page I </title>
    </head> 

    <body>  
        Age: 
        <input type="text" id "cage" name="cage" size="10"
    onBlur=show();> 

    </body>
</html>

Solution

  • The onBlur event fires when the current control loses focus. When a control has focus, meaning that it's currently "selected", things that can cause it to lose focus include clicking on another control or pressing the tab key.

    The reason your method does not work properly is because it has a small error. Try this:

    <html> 
        <head> 
            <script> 
                function show(el) 
                { 
                  var age = parseInt(el.value); 
                  if (age<=18) 
                    alert("access denied"); 
                  else 
                    alert("Welcome"); 
                } 
            </script> 
            <title> New Page I </title> 
        </head>  
    
        <body>   
            Age:  
            <input type="text" id="cage" name="cage" size="10" onBlur="show(this);" />  
         </body> 
    </html>