Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters to jQuery document.ready() function (ASP.NET MVC, C#)

I would like to pass a parameter to the jQuery document.ready() function from my View:

$(document).ready(function (parameter){
        $('select[name=Product]').val(parameter);
});

How can I fire the event from my View and pass the parameter? I use Razor as View engine.

Thanks

like image 448
CiccioMiami Avatar asked May 12 '11 10:05

CiccioMiami


People also ask

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

jQuery ready() Method The ready event occurs when the DOM (document object model) has been loaded. Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above. The ready() method specifies what happens when a ready event occurs.

What is $( document .ready () and $( window .load () in jQuery which one will be fired first?

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.

What is the importance of $( document ready () 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.

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

We can have multiple document. ready() function in our code but only one body. onload() is allowed.


1 Answers

You can't. The document.ready function doesn't take parameters. You could for example define this parameter as a global variable in your view:

<script type="text/javascript">
    var model = @Html.Raw(Json.Encode(Model));
</script>

and then in your separate javascript file use this global variable:

$(function() {
    $('select[name=Product]').val(model.SomeProperty);
});
like image 195
Darin Dimitrov Avatar answered Sep 21 '22 12:09

Darin Dimitrov