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
To avoid using global variables, you can define a closure and then returning this function to
ready()
:and then call
ready()
:You can also define the start function in a external .js file and calling ready (for example) in your main html file. Example: external script.js:
html file:
Calling
ready()
in the latter file allows you to pass server parameters to your functions. Example (using PHP. In this case you must change the extension from html to php to this file):You can effectively accomplish this with a closure. That is, if you are calling something like
$(document).ready(startup)
then you can easily rewritestartup
so that you can call it with a parameter, e.g.$(document).ready(startup(7))
. Pablo gave an excellent underrated answer, and it is worth giving a more detailed example.Example
Here is a page which displays an alert, invoked by
$(document).ready()
, that calculates6*9
:Say you want to replace "9" with a variable parameter. The 4-step recipe to do this is:
return function() {...}
.Applying this to the above code:
This displays the alert "6 * 7 = 42".
What's Happening?
$(document).ready()
takes as its parameter a function. This is why it is called in the first version above with juststartup
as the parameter. In contrast if you called it withstartup()
you wouldn't be passing in thestartup
function anymore, you would be passing in the return value ofstartup
.Since
$(document).ready()
takes a function as its parameter, that's what we give it:startup
is transformed in the second version above into a function that returns a function, which has the parameterx
set to the value we pass it initially. That is,startup(7)
returns a function to$(document).ready()
that has the value ofx
set to7
.OP's Question
To specifically apply this to the OP's question, rewrite that call as
where
'name'
can be any other value that gets substituted forx
. No need for global variables.More information: JavaScript closures.
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:
and then in your separate javascript file use this global variable:
You can simply echo your parameter value into the Javascript code if its inline in your view.