loyd
loyd

Reputation: 147

Javascript: Trying to use var in switch: "var is declared but its value is never read"

In Javascript I declared var x and var y in a function:

var x = document.getElementById("x").value;
var y = document.getElementById("y").value;

I did this because I need to use document.getElementById several times.

Also in this function I have a switch-case. In all cases I need to use var x and var y.

I get the warning that var x and var y is never read.

I used a if-Statement before but I think that using a switch-case is better in this situation.

When I use document.getElementById("x").value instead of var x it works but I don't want to call document.getElementById in 10 cases.

function showOptions(s) {

    var x = document.getElementById("x").value; //"never used"
    var y = document.getElementById("y").value; //"never used"

        switch (s[s.selectedIndex].id) {

            case "case1":
                document.getElementById("x").value = "1"; //works
                document.getElementById("y").value = "2"; //works
                break;

            case "case2":
                x = "2"; //does not work
                y = "4"; //does not work
                break;
    }

Upvotes: 1

Views: 271

Answers (2)

Quentin
Quentin

Reputation: 944009

var cpu = document.getElementById("x").value; //"never used"

The value property of an element is a string. When you copy the value of that property to a variable, you copy the string.

cpu = "2"; //does not work

If you copy a new value to the variable, then you change the value of the variable.

It is not a reference to the value property of an object. It has no connection to the element.

If the value you copied was a reference to an object:

var cpu = document.getElementById("x");

… then you could access the object and update the property:

cpu.value = "2";

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386680

You need to take the object reference, instead of a variable with a primitive value.

function showOptions(s) {
    var cpu = document.getElementById("x"); // take object
    var ram = document.getElementById("y");

    switch (s[s.selectedIndex].id) {
        case "case1":
            cpu.value = "1"; // use property of object
            ram.value = "2";
            break;
        case "case2":
            cpu.value = "2";
            ram.value = "4";
            break;
    }
}

Upvotes: 2

Related Questions