Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery function not firing at all

Tags:

jquery

Real Dumb question. I figured I would have gotten this straight by now, but I am obviously missing something. I want my function to fire as soon as the page loads to check the value of a variable and make a button appear or dissapear based on that value. But the function I wrote never gets called. I place the function inside a $.Load() and $(document).ready jquery call. How can I get this function to fire?

 $(document).ready(function () {
        debugger;        
        (function () {           
        debugger;
        var $b = '<%=toggle %>';
        var buttonTog = $("#test1");
        var buttonTog1 = $("#Submit1");
        if($b=="1")
        {
            debugger;
            buttonTog1.css({
                display: 'block'
            })
            buttonTog.css({
                display: 'none'
            });
        }
        else if($b=="0")
        {
            debugger;
            buttonTog1.css({
                display: 'none'
            })
            buttonTog.css({
                display: 'block'
            });
           }            
       });
       ...
    });

As you can see, I have multiple debugger statements in there that just don't get hit... When I hit $(document).ready and I get into the first debugger statement, It simply doesn't touch the next function? I don't get it? It goes right over it? Can you not call a function inside the .ready(function())? Definitly need to get some research done.

like image 358
SoftwareSavant Avatar asked Dec 04 '22 19:12

SoftwareSavant


1 Answers

You define an anonymous function but you never call it. Here's how to auto-invoke the anonymous function:

$(document).ready(function () {
    (function() {
        var buttonTog = $("#test1");
        var buttonTog1 = $("#Submit1");
        ...
    })(); // <!-- notice the (); at the end
});

This being said, I can hardly see the usefulness of using this anonymous auto-invoking function inside the document.ready callback which itself is an anonymous function. Things start to get really private here :-)

You could simply write the code inside it:

$(document).ready(function () {
    var buttonTog = $("#test1");
    var buttonTog1 = $("#Submit1");
    ...
});

I suspect that you might be missing some important concepts about the $(document).ready function and its syntax. I would recommend you checking the documentation for more examples.

like image 191
Darin Dimitrov Avatar answered Dec 31 '22 15:12

Darin Dimitrov