Link to home
Create AccountLog in
Avatar of NewWebDesigner
NewWebDesigner

asked on

Why is my alert returning undefined instead of the id of the element?

Hello,

when the page loads, I want alerts to tell me the id's of the input elements.  Instead what I am getting are three alerts with 'undefined'.  How do I correct this?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
window.onload = initPage;

function initPage() {
	
var pics = document.getElementById("pictures").getElementsByTagName("input")
    for (i = 0; i < pics.length; i++) {
		pics[i] = displayID();

	}
}

function displayID() {
	alert(this.id);
}
</script>

</head>

<body>
<div id="pictures">
<input id=<?php echo "\"lala\"" ?> type="text" name="input1"></input>
<input id="input2" type="text" name="input2"></input>
<input id="input3" type="text" name="input3"></input>
</div>
</body>
</html>

Open in new window

Avatar of Badotz
Badotz
Flag of United States of America image

Because this refers to the Document, and there is (most likely) no id attribute for it.
ASKER CERTIFIED SOLUTION
Avatar of dotnetbrit
dotnetbrit

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
If one cannot fathom JavaScript, then good luck with jQuery.
Avatar of hielo
change:
for (i = 0; i < pics.length; i++) {
		pics[i] = displayID();

	}

to:
for (i = 0; i < pics.length; i++) {
		pics[i] = displayID; //you should  NOT use parentheses to assign a function reference

	}

Open in new window

Ignore my previous comment. I misread your question.
Avatar of EndersDev
EndersDev

Your "this" was undefined. Send the object to the display function. Also note you weren't returning anything from displayID so don't assign the alert function to it.

 
<script type="text/javascript">
window.onload = initPage;

function initPage() {
	
var pics = document.getElementById("pictures").getElementsByTagName("input")
    for (i = 0; i < pics.length; i++) {
		displayID(pics[i]);

	}
}

function displayID(ob) {
	alert(ob.id);
}
</script>

Open in new window