Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - run a function of change() and ready()

Tags:

jquery

I have a jquery code which run on .change(). But I want to run the same code on jquery .ready(), but it is not working.

Here is my code:

    jQuery('.nhp-opts-select-hide-below').change(function(){
        var option = jQuery('option:selected', this);
        if(option.data('show').length > 0 || option.data('hide').length > 0){
            jQuery(option.data('show')).each(function(){
                if(jQuery(this).closest('tr').is(':hidden')){
                    jQuery(this).closest('tr').fadeIn('fast');
                }
            });
            jQuery(option.data('hide')).each(function(){
                if(jQuery(this).closest('tr').is(':visible')){
                    jQuery(this).closest('tr').fadeOut('fast');
                }
            });

        }else{
            jQuery(option.data('show')).each(function(){
                if(jQuery(this).closest('tr').is(':visible')){
                    jQuery(this).closest('tr').fadeOut('fast');
                }
            });
            jQuery(option.data('hide')).each(function(){
                if(jQuery(this).closest('tr').is(':hidden')){
                    jQuery(this).closest('tr').fadeIn('fast');
                }
            });     
        }
    }); 

please tell me how to run the above code on jquery ready??

like image 258
user007 Avatar asked Jun 22 '13 04:06

user007


People also ask

What is difference between $( document .ready function () vs $( function ()?

The key difference between $(document). ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.

How do you call a function in document ready jQuery?

Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready. // A $( document ).ready() block.

Can I have multiple jQuery document ready () method in a HTML page?

Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.

What is $( document ready () method in jQuery?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.


1 Answers

Just call .change() with no arguments. Put that whole thing inside of your ready handler, and then:

jQuery(function($) {
    $('.nhp-opts-select-hide-below').change(function(){
        // snip...
    }).change(); // that's it
});
like image 106
Matt Ball Avatar answered Sep 18 '22 12:09

Matt Ball