0

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

2
  • An a element does not have a .value property. Nor is its value attribute valid. Commented Dec 30, 2014 at 15:03
  • Since value is not valid, it becomes a custom attribute.. May be accessed by getAttribute("value") Commented Dec 30, 2014 at 15:05

2 Answers 2

1

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')
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.