opbeta
opbeta

Reputation: 3

How to condense onclick code to be dynamic

I am trying to get this onclick function code to be dynamic. I do not want to have 50 blocks of code for all the states. He is a quick snippet of the code

    var Ohio=function(){
    document.getElementById('texas').style.display='none';
    document.getElementById('florida').style.display='none';
    document.getElementById('ohio').style.display='block';

    }

and so on and so forth.....

the html that passes the function:

<li onclick="Ohio()" id="ohio" >

and so on and so forth How would I go about condensing this to make it smaller and dynamic?

Upvotes: 0

Views: 62

Answers (1)

nnnnnn
nnnnnn

Reputation: 150030

If you can update the elements to have a common class, e.g., class="state", then:

var SetState = function(state) {
    var s = document.getElementsByClassName("state"),
        i;
    for (i=0; i < s.length; i++)
        s[i].style.display = 'none';

    document.getElementById(state).style.display = 'block';
};

That is, loop through all elements with the state class and hide them, then show just the one that was passed into the function with:

SetState('ohio');

Alternatively, if you can't change the html, put all the state names in an array and loop through the array to hide them.

Upvotes: 2

Related Questions