Jonathan
Jonathan

Reputation: 1

document.getElementByName()[0] undefined

This is my js function

function toggleCountry(country)
{
    var elem = document.getElementsByName(country)[0].value;
    alert(elem);
}

Its being called onclick event

<a href="#" onclick="toggleCountry('usa');"><div class="navBarItems">USA</div></a>

I have another div with the attribute name="usa" and I want to search for it and disable the text. However, I always get undefined as it returns in my alert.

Edit: Its a div tag.

Upvotes: 0

Views: 266

Answers (2)

Stuart Kershaw
Stuart Kershaw

Reputation: 17671

document.getElementsByName(name) requires that you make use of the name="" attribute.

With that in place, try changing:

var elem = document.getElementsByName(country)[0].value;

To:

var elem = document.getElementsByName(country)[0].innerHTML;

(provided this is your goal)

.value is the wrong method here (there's no value attribute on your element). I was able to access the .innerHTML just fine, so your function is selecting the appropriate element. If .innerHTML is not what you want, you can substitute that for another method. I'm not entirely sure what you're reaching for here, but hopefully this jsfiddle helps:

http://jsfiddle.net/S68qr/

Upvotes: 3

gonzalovazzquez
gonzalovazzquez

Reputation: 166

I am not sure of your implementation and Stuart Kershaw already provided a great solution.

Another approach would be to change your HTML to provide a more dynamic selection.

    <select onchange="toggleCountry(this.value)">
       <option value="USA">USA</option>
       <option value="CDN">CDN</option>
    </select>

And you can use this function to retrieve the value.

function toggleCountry(country)
{
    alert(country);
}

http://jsfiddle.net/LzubU/

Upvotes: 0

Related Questions