Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"function" is not defined error in Javascript: what is the right way to call my function?

I understand a bit because of this post: JQuery, setTimeout not working why it's not working, but keeping everything this way, what is the right way to call _finalvalidate() inside my div?

 <script type="text/javascript">

$(document).ready(function(){

//On Submitting
function _finalvalidate(){
    alert('ppp');
    if(validateName() & validateEmail() & validatePhone()){
        alert('OK');
        return true
    }
    else{
        alert('false');
        return false;
    }
}
});

</script>


<div onclick="_finalvalidate();"> Take action </div>
like image 536
Joel Avatar asked Dec 27 '22 10:12

Joel


1 Answers

The jQuery way of doing it would be something like:

<script type="text/javascript">

    $(document).ready(function(){

        //When clicking on the div, execute this 
        $("#validation").click(function() {
            alert('ppp');
            if(validateName() & validateEmail() & validatePhone()){
                alert('OK');
                return true
            }
            else{
                alert('false');
                return false;
            }
        });
    });

</script>
....
<div id="validate"> Take action </div>

If you really want to use the javascript function style, you gonna have to put the function outside the document.ready() function and then you'll be able to call it with the onclick attribute:

<script type="text/javascript">

    function _finalvalidate(){
        alert('ppp');
        if(validateName() & validateEmail() & validatePhone()){
            alert('OK');
            return true;
        }
        else{
            alert('false');
            return false;
        }
    }   


</script>
....
<div onclick="_finalvalidate();"> Take action </div>

In this case you don't have anymore jQuery involved.

like image 73
talnicolas Avatar answered May 16 '23 17:05

talnicolas