Reginald Maravilla
Reginald Maravilla

Reputation: 9

Syntax Error in Basic Javascript Function

I keep getting errors when debugging in IE. This is a basic hide function.

idHide is the id of the field to be hidden idCondition is the id of the reference field the condition is compared upon value is the value that would satisfy the condition

function hideOnCondition(idHide, idCondition, value)
{    
    if (document.getElementById[idCondition] = value)
    {    
        document.getElementById(idHide).style.display = "none";         
    }
    else
    {           
        document.getElementById(idHide).style.display = "";
    }
}

I always encounter the error in:

if (document.getElementById[idCondition] = value)

"the value of the property is null or undefined not a function object"

Then I tried changing "getElementById" with "all". then changed the brackets to parentheses, still nothing, only for the line to be highlighted in yellow.

Im sorry, I'm just stumped. Again, thank you all for understanding.

Upvotes: -1

Views: 59

Answers (4)

Nephi
Nephi

Reputation: 55

function myFunction(option, value, div) {

    //get the element you want to hide by it's ID
    var x = document.getElementById(div); 

    //if the option you selected is coresponding to the given value 
    //hide the earlier selected element
    if (option === value) {
        x.style.display = "none";
    } else {
        x.style.display = "block";
    }
}

This should do it.

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68433

Two issues I could see

  • using = instead of === and not comparing value instead only comparing the the output of document.getElementById[idCondition] with value.

  • using [] instead of invoking the function using ()

Although, none of these would cause the syntax error as you have claimed in your post.

You can simplify it as

var getEl = (id) => document.getElementById(id);
function hideOnCondition(idHide, idCondition, value)
{    
    getEl(idHide).style.display = getEl(idCondition).value == value ? "none" : "";
}

Upvotes: 0

Yosvel Quintero
Yosvel Quintero

Reputation: 19090

Instead of an assignment you should use the comparison operator Identity / strict equality (===):

function hideOnCondition(idHide, idCondition, value) {
    const result = document.getElementById[idCondition] === value ? 'none' : '';
    document.getElementById(idHide).style.display = result;
}

Upvotes: 0

Hendry
Hendry

Reputation: 900

  • You were using square brackets instead of parentheses
  • === should be used for comparing not =

.

function hideOnCondition(idHide, idCondition, value)
{    
    if (document.getElementById(idCondition) === value) // <- fix here
    {    
        document.getElementById(idHide).style.display = "none";         
    }
    else
    {           
        document.getElementById(idHide).style.display = "";
    }
}

Upvotes: 1

Related Questions