valentinosael
valentinosael

Reputation: 25

undefined value in javascript

I have this function to dynamically create a list from an array

function fill1(arr) {
    var out = "";
    var i;
    for(i = 0; i < arr.length; i++) {
        var a=arr[i].code;
        var b=arr[i].name;
        out += '<li><a href="" onclick="myfunction(this)" id="'+arr[i].code+'" value="'+arr[i].name+'">' + 
        b + '</a></li>';
    }
    document.getElementById("instrumental").innerHTML = out;
}

and this function for alert

function myfunction(elem) {
    var x=elem.id;
    var c=document.getElementById(x).value;
    alert(c);
}

When I alert x its ok but when i alert c its showing undefined

Upvotes: 0

Views: 85

Answers (2)

EasyPush
EasyPush

Reputation: 776

Instead of setting a "value" property on an "a" tag which is not a valid attribute you want to set a "data-value" attribute instead, like so:

out += '<li><a href="" onclick="myfunction(this)" id="'+arr[i].code+'" data-value="'+arr[i].name+'">' + 

These "data-" attributes are a way to allow you to add your own attributes to elements that do not affect how they are rendered by the browser.

You also can't simply access attributes on DOM elements in the way you are attempting, you need to do it like this

var c=document.getElementById(x).getAttribute('data-value')

Upvotes: 1

Giacomo Negretti
Giacomo Negretti

Reputation: 89

value is not a valid attribute for tag a If you are using HTML you can convert your code to use data attribute

Upvotes: 0

Related Questions