I have been having a lot of trouble trying to get value into javascript and pass it to alert. Here is the code that I use to pass the value....
<img onclick="handpost()" id="colorface" name="red" src="http://www.asl-ela.org/image/redface.png" alt="Red face" /></a>
Then I use function to get the data from img tag....
<script type="text/javascript">
function handpost() {
var color = document.getElementById('colorface').name;
alert(color);
}
</script>
I keep getting alert box saying undefined. What does that mean?!?!?!
3 Answers 3
It means exactly what it reads: document.getElementById('colorface').name is undefined. document.getElementById('colorface') may exist but it doesn't have property name. Try document.getElementById('colorface').getAttribute('name').
name is not standard attribute of img but if you add it then you can access it.
enter image description here
2 Comments
name to .getAttribute('name') and it works.Use the following instead :
var color = document.getElementById('colorface').getAttribute('name');
Comments
Not sure how could you get it as undefined
Element.name,
namegets or sets the name property of a DOM object; it only applies to the following elements:<a>,<applet>,<button>,<form>,<frame>,<iframe>,<img>,<input>,<map>,<meta>,<object>,<param>,<select>, and<textarea>(From MDN)
function handpost() {
var color = document.getElementById('colorface').name;
alert(color);
}
<img onclick="handpost()" id="colorface" name="red" src="http://www.asl-ela.org/image/redface.png" alt="Red face" />
nameis not an<img>propertynameis a property of img element. You should usegetAttributeto get its value, try thisdocument.getElementById('colorface').getAttribute('name')nameis not a standard property onimgattributes, you shouldn't use it. Instead, it is better to usedata-nameas the wholedata-*realm as been reserved for custom values. developer.mozilla.org/en-US/docs/Web/Guide/HTML/… .. these values can also be accessed via jQuery'sdatamethod orgetAttribute('data-name')