KPopOG
KPopOG

Reputation: 85

Changing Variable Passed as Parameter in Javascript

I've recently been working on a project making a form. I have a button setup to make more fields appear and people need them, but am currently using 3 seperate functions and know there must be a way to shorten my code.

I'm hoping to pass the variable that I want to work with as a parameter. For example, I'd like to use something like

var first = 1
var middle = 1
var last = 1

function increment("first, middle or last") {
"parameter"++
} 
console.log(parameter) //outputs "2"

Here's the 3 functions I'm using right now that I'd like to condense into just 1.

var first = 1;
var middle = 1;
var last = 1


function firstNameFields() {
    first = first + 1;
    var x = document.getElementById("firstField" + first);
    if (first >= 0) {
        x.style.display = "table-row";
    } else {
        x.style.display = "none";
    }
    if (first >= 10) {
        document.getElementById("first").style.display = "none";
    }
}

function middleNameFields() {
    middle = middle + 1;
    var x = document.getElementById("middleField" + middle);
    if (middle >= 0) {
        x.style.display = "table-row";
    } else {
        x.style.display = "none";
    }
    if (middle >= 10) {
        document.getElementById("middle").style.display = "none";
    }
}

function lastNameFields() {
    last = last + 1;
    var x = document.getElementById("lastField" + last);
    if (last >= 0) {
        x.style.display = "table-row";
    } else {
        x.style.display = "none";
    }
    1;
    if (last >= 10) {
        document.getElementById("last").style.display = "none";
    }
}

Thank you so much!

Upvotes: 1

Views: 471

Answers (1)

Pointy
Pointy

Reputation: 413720

You can't modify plain variables with a function in the way you describe, but there are alternatives. You can use an object with properties instead of a collection of variables, and then pass the name of the property (i.e., a string) to the function:

var name = {
  first: 1, middle: 1, last: 1
};

function increment(part) {
  name[part]++;
}

Now increment("first") will increment name.first.

Upvotes: 2

Related Questions