You can effectively accomplish this with a closure. That is, if you are calling something like $(document).ready(startup)
then you can easily rewrite startup
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 calculates 6*9
:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function startup() {
alert('6 * 9 = ' + 6 * 9);
}
</script>
</head>
<body>
Hello!
<script>
$(document).ready(startup);
</script>
</body>
</html>
Say you want to replace "9" with a variable parameter. The 4-step recipe to do this is:
- Parameterize the function.
- Wrap the function body in a closure. That is,
return function() {...}
.
- Parameterize the body.
- Call the function with the parameter.
Applying this to the above code:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function startup(x) { // Step 1 - Parameterize the function
return function() { // Step 2 - Put body in "return function() {...}"
alert('6 * '+x+' = ' + 6 * x); // Step 3 - Parameterize the body.
} // (closing brace for step 2)
}
</script>
</head>
<body>
Hello!
<script>
$(document).ready(startup(7)); // Step 4 - Call function with parameter.
</script>
</body>
</html>
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 just startup
as the parameter. In contrast if you called it with startup()
you wouldn't be passing in the startup
function anymore, you would be passing in the return value of startup
.
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 parameter x
set to the value we pass it initially. That is, startup(7)
returns a function to $(document).ready()
that has the value of x
set to 7
.
OP's Question
To specifically apply this to the OP's question, rewrite that call as
$(document).ready((function(x) { return function() {
$('select[name=Product]').val(x);
}})('name'));
where 'name'
can be any other value that gets substituted for x
. No need for global variables.
More information: JavaScript closures.