Her Man Her Man - 2 months ago 11
Javascript Question

How to combine 4 the same functions into one new function that can be reused

I made some functions, but they are all doing approximately the same thing.
I would like to combine those functions into one new function that can be reused in case i need one more new function like this.. Is it possible to do so or am i just wasting your and my time?

Here is the code:

function getBinding(selectedBinding) {
var b = elems.binding;
var selectedBinding = b.options[b.selectedIndex].value;
return selectedBinding;

// Getting the holes value
function getHoles(selectedHoles) {
var h = elems.holes;
var selectedHoles = h.options[h.selectedIndex].value;
return selectedHoles;

// Getting the paper weight value
function getPaperWeight(selectedPaperWeight) {
var pW = elems.paperWeight;
var selectedPaperWeight = pW.options[pW.selectedIndex].value;
return selectedPaperWeight;

// Getting the staples value
function getStaples(selectedStapling) {
var s = elems.stapling;
var selectedStapling = s.options[s.selectedIndex].value;
return selectedStapling;

any suggestions?

Thanks a lot!


You could take the element as parameter.

function getValue(element) {
    var e = elems[element];
    return e.options[e.selectedIndex].value;