Reputation: 18630
I have some javascript where I append an option to a select:
var myuniqueddl = $('#myuniqueddl');
$("<option value='0'>--- Select a value ---</option>").appendTo(myuniqueddl);
I'm actually trying to do this for another select as well.
I'm wondering to avoid code duplication should I be passing the ddl to a method to do this?
function(someType ddl)
{
$("<option value='0'>--- Select a value ---</option>").appendTo(ddl);
}
Is this a bad idea to be passing a select to a method?
Any better way of doing this?
If this way is ok what type do I pass it in as?
Upvotes: 0
Views: 707
Reputation: 239230
Firstly, yes, it's completely valid to pass a select
element into a function to reduce code duplication. In this case, it seems like you're worried about having to type the same function call (appendTo
) twice, which really isn't duplication.
Secondly, you cannot specify any type for a JavaScript function parameter. Variables in JavaScript are dynamically typed. You simply specify the variable name:
function myFunction(ddl) {
$("<option value='0'>--- Select a value ---</option>").appendTo(ddl);
}
Upvotes: 5
Reputation: 50592
Javascript functions do not use type hinting, so your function signature:
function(someType ddl)
.. is not valid.
Further, I suggest making your function a little more flexible, and to eliminate the creating of DOM elements by passing strings to jQuery (not efficient, see this benchmark):
var addOption = function(sel, text, value) {
if (typeof value == 'undefined')
value = text;
sel.options[sel.options.length] = new Option(text, value);
}
// usage: addOption($('#myuniqueddl'), '--- Select a value ---');
// or: addOption($('#myuniqueddl'), '--- Select a value ---', 0);
Documentation
Upvotes: 3
Reputation: 25684
There is nothing wrong with this, but let me give you a valid example, as your code has some syntax errors.
function(ddl)
{
$("<option value='0'>--- Select a value ---</option>").appendTo(ddl);
}
If this way is ok what type do I pass it in as?
Javascript doesn't use types the same way c# or java do. Just pass a variable, similar to the code above.
Upvotes: 1
Reputation: 9110
If this way is ok what type do I pass it in as?
It should be jQuery element similar to:
var myuniqueddl = $('#myuniqueddl');
Example:
function addOption(el)
{
$("<option value='0'>--- Select a value ---</option>").appendTo(el);
}
var myuniqueddl = $('#myuniqueddl');
var myuniqueddl2 = $('#myuniqueddl2');
addOption(myuniqueddl);
addOption(myuniqueddl2);
Or directly:
addOption($('#myuniqueddl'));
addOption($('#myuniqueddl2'));
Upvotes: 3