Getting getElementById is Undefined - javascript

Here's my code:
<html>
<header>
<title>Checkup Date</title>
<script type="text/javascript">
function datechange() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest(); }
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject
("Microsoft.XMLHTTP");
}
var tr = getElementsById(nameUpdate)
var tds = tr.getElementsByTagName('td');
var user = "";
var date = "";
for(var i = 0, len = tds.length; i < len; ++i) {
user = tds[0];
date = tds[3];
}
var url = "changedate.psp"
var params = "user=" + user + "&date=" + date;
xmlhttp.open("GET", url + "?" + params, true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
</script>
</header>
<body>
<%
Python that doesn't matter
%>
<%= More Python %>
</body>
</html>
My outputted HTML:
<tr id="TL-D03">
<td>nobody</td>
<td>TL-D03</td>
<td>2010-01-01</td>
<td>
<input type="checkbox" onclick="var nameUpdate = 'TL-D03'; datechange();">
What am I doing wrong here? It says getElementById is undefined.

getElementById is a function of document:
var tr = document.getElementById("nameUpdate")
MDN: https://developer.mozilla.org/en/DOM/document.getElementById

Problem 1: you're calling getElementsById. IDs are unique: the function is getElementById. No s.
Problem 2: getElementById is not a global function. You need to call it on the document object:
var tr = document.getElementById(nameUpdate)
After all, your script could reference more than one document (for example, with an iframe), so you need to be explicit about where you expect the element to be.

Also try changing:
<input type="checkbox" onclick="var nameUpdate = 'TL-D03'; datechange();">
to this:
<input type="checkbox" onclick="datechange('TL-D03')">
and
function datechange() {
to this
function datechange(nameUpdate) {
makes more sence

It's document.getElementById(), not getElementsById(), as it only returns one element.
The latter would not be very useful, since id attributes must be unique within an HTML document.

you need to use document.getElementById("yourelementid")

The reason it doesn't work is that var scopes a variable to the function it is defined in, so it isn't readable outside the anonymous function assigned to the onclick handler.
In more general "wrongness" terms, passing data about using globals is generally a bad idea.
Pass it as an argument instead.
function datechange(nameUpdate) {
and
datechange('TL-D03');

Related

Content Fetching from XML file

I have a xml content as below
<tty>
<xyz id="1">
<yzx>ghs</yzx>
<dfg>kli</dfg>
</xyz>
<xyz id="2">
<yzx>sss</yzx>
<dfg>ddd</dfg>
</xyz>
</tty>
I need to fetch the content of xyz also and when I try to do so I face an error stating
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "file.xml",false);
xmlHttp.send();
xmlDoc = xmlHttp.responseXML;
var wee= xmlDoc.getElementsByTagName("xyz");
for(var i=0; i<wee.length;i++){
var name = wee[i].childNodes[0].nodeValue;
var yzx = wee[i].childNodes[1].nodeValue;
var dfg= wee[i].childNodes[2].nodeValue;
error is
Cannot read property childnode
My output should have like below
name 1
yzx ghs
you are using getElementsByTagName twice :)
wee is already all of the <xyz> tags, and there are no more <xyz> tags below it. That means the getElementsBbyTagName('xyz') inside the for loop will return nothing.
You probably just want
for(var i = 0; i < wee.length; i++) {
var name = wee[i].childNodes[0].nodeValue; // "yzx" node
}
instead.

print entire xml data and tags in html - javascript [duplicate]

I want to convert an xml element like this:
<asin>​B0013FRNKG​</asin>​
to string in javascript
I used XMLSerializer:
new XMLSerializer().serializeToString(xml);
the string only shows on alert() and in the console. On the page it just says
[object Element][object Element]
I want to get the string.
You haven't told us how you go about displaying that object. XMLSerializer works on DOM nodes, so your object has to be added somewhere, for example:
document.getElementById('SomeDiv').appendChild(xml);
and if you just want the full xml string to be displayed:
var xmlText = new XMLSerializer().serializeToString(xml);
var xmlTextNode = document.createTextNode(xmlText);
var parentDiv = document.getElementById('SomeDiv');
parentDiv.appendChild(xmlTextNode);
<script type='text/javascript'>
function xmlToString(xmlData) {
var xmlString;
//IE
if (window.ActiveXObject){
xmlString = xmlData.xml;
}
// code for Mozilla, Firefox, Opera, etc.
else{
xmlString = (new XMLSerializer()).serializeToString(xmlData);
}
return xmlString;
}
</script>
use this in case of IE for browser compatibility issues.
function getXmlString(xml) {
if (window.ActiveXObject) { return xml.xml; }
return new XMLSerializer().serializeToString(xml);
}
alert(getXmlString(xml));
Did you try enclosing the result like in…
(new XMLSerializer()).serializeToString(xml)
Also, I'd use console instead to see the content better:
console.log((new XMLSerializer()).serializeToString(xml));
If the DOM element <asin>​B0013FRNKG​</asin>​ is stored in the object element, then you can access the value using:
element.textContent
follow this to print,append data from xml data stored as string inside javscript
txt="<papers>"+"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<papers>";
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
x=xmlDoc.getElementsByTagName("paper");
for (var i = 0; i < x.length; i++) {
var athor =x[i].childNodes[0].firstChild.nodeValue;
var title = x[i].childNodes[1].firstChild.nodeValue;
var path = x[i].childNodes[2].firstChild.nodeValue;
var tack =x[i].childNodes[3].firstChild.nodeValue;
//do something with these values...
//each iteration gives one paper details
var xml=document.getElementById("element_id");//<div id="element_id"></div>
var li = document.createElement("br");// create a new <br>
newlink = document.createElement('A'); // creating an <a> element
newlink.innerHTML = athor;// adding <a>athor value here</a>
newlink.setAttribute('href', path);//
newlink.appendChild(li);// athor<br>
document.getElementById("element_id").appendChild(newlink);//finaly it becomes <div id="element_id">athor<br></div>
}

displaying xml data with javascript, issue at end of function?

Trying to make a text/sample page for a future project. I want to be able to list a certain amount of objects at a time from the xml document, with a button to load the next however many. Sort of like a browsing catalog. Here's what I got, and I'm pretty sure the problem is at the end of the listbythree function. I just don't know how to plug that function into the specified div element on pageload. any help?
<!DOCTYPE html />
<html>
<head>
<script>
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.open("GET","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var i=0;
var x=xmlDoc.getElementsByTagName("book");
function listbythree()
{
for (i;i<3;i++)
{
document.write("<div style='display:inline;float:left;background-color:#ffff99;padding:10px;width:300px;height:210px;margin:5px;font-size:14px;'><img style='float:left;padding-right:4px' src=");
document.write(x[i].getElementsByTagName("cover")[0].childNodes[0].nodeValue + " />");
document.write("<em>" + x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue + "</em><br/>");
document.write(x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue + "<br/>");
document.write(x[i].getElementsByTagName("pub")[0].childNodes[0].nodeValue + "<br/>");
document.write(x[i].getElementsByTagName("edition")[0].childNodes[0].nodeValue + "<br/>");
document.write(x[i].getElementsByTagName("genre")[0].childNodes[0].nodeValue + "<br/>");
document.write("Have I Read: " + x[i].getElementsByTagName("read")[0].childNodes[0].nodeValue);
document.write("</div>");
}
document.getElementById("booksbythree").innerHTML=this;
};
function next()
{
if (i<x.length-1)
{
i+3;
listbythree();
}
}
function previous()
{
if (i>0)
{
i-3;
listbythree();
}
}
</script>
</head>
<body onload="listbythree()">
<div id="booksbythree"></div><br/><br/>
<input type="button" onclick="previous()" value="<<" />
<input type="button" onclick="next()" value=">>" />
</body>
</html>
Your for loop only loops when i<3, so it will never show any elements further than the third. You can do the following to fix this. Also your next button is adding 3 to i when your for loop is also adding to i, this would make you skip 3 elements each time you click next.
function listbythree()
{
var j = i+3;
for (i;i<j&&i<x.length;i++)
{
....
}
}
function next()
{
if (i<x.length-1)
{
listbythree();
}
}
On a second note I would suggest that you use jQuery, it can make the AJAX and XML parsing much easier.

Selecting the innerHTML of two <td>'s inside a <tr id="blahblahblah">

Ok, so I've got an onclick event (CF-D07 is an example, these are generated programmatically based on a MySQL database):
<input type="checkbox" onclick="var nameUpdate = 'CF-D07';
datechange();" id="CF-D07">
So then, under datechange(), I have this:
function datechange() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest(); }
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject
("Microsoft.XMLHTTP");
}
document.body.getElementsByTagName("tr").getElementsById(nameUpdate);
// This section isn't done yet.
// var url = "changedate.psp"
// var params = "user=" + nameUpdate
// xmlhttp.open("GET", url + "?" + params,false);
// xmlhttp.send();
// xmlDoc=xmlhttp.responseXML;
}
The important part of this is this part of the code:
document.body.getElementsByTagName("tr").getElementsById(nameUpdate);
How do I make it so that I get all of the elements with the tag, that then have the id of nameUpdate, based on the onclick event? And then after that, how do I select the innerHTML of the first two 's in the and put it into separate variables?
If I'm understanding you correctly, you should never have more than one element with the same ID on any page. If you need to classify html elements, use the class attribute.
To get the inner html of elements, you can use aptly named innerHTML property of the DOM element:
function datechange(nameUpdate) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// document.body.getElementsByTagName("tr").getElementsById(nameUpdate);
var trs = document.getElementByClassName(nameUpdate);
for(var i = 0, len = trs.length; i < len; ++i) {
var html = tr.innerHTML;
// Do what you need to with HTML
}
}
With the above code, your original HTML snippet could look like this:
<input type="checkbox" onclick="datechange('CF-D07')">
This also assumes you'd have a tr somewhere that looks something like this:
<tr class="CF-D07">
<td>...</td>
<td>...</td>
</tr>
To access the <td> elements of a given <tr>, you can use the children property for all child elements, or you can use getElementsByTagName directly on the tr element:
var tr = ... // get the TR somehow
var tds = tr.getElementsByTagName('td');
var allHTML = "";
for(var i = 0, len = tds.length; i < len; ++i) {
allHTML += tds[i].innerHTML;
}
// Do something with allHTML, which is the inner html of all tds put together

Passing element in XMLHttpRequest to one function but second one also knows, why?

I am working on the jsp/servlet/ajax application.
I use XMLHttpRequest to pass values from the JSP page to servlet, which retrieve data from the database and returns XML to the JSP.
The code works but there is one thing I do not understand.
Here is a JSP part
<body>
<label>Longitude</label><input type="text" id ="lat" value="40.799559" />
<br/>
<label>Latitude</label><input type="text" id="lon" value="-74.481386" />
<br/><br/>
<input type="button" onclick="checkGPSCoords(document)" value="Test" />
<br/><br/>
<input type="text" id ="dbCounty" readonly/>
<br/>
<input type="text" id ="dbMuni" readonly />
<br/><br/>
</body>
I am passing a document element into the JavaScript
Here is a script:
<script type="text/javascript" language="JavaScript">
var req;
var isIE;
function initRequest() {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function checkGPSCoords(currentWindow){
var lat= currentWindow.getElementById("lat").value;
var lon = document.getElementById("lon").value;
//alert("lon:" + lon);
initRequest();
req.open("GET","./lonlat?lat="+ lat + "&lon=" + lon);
req.onreadystatechange = retrieveMuniCntyNames;
req.send(null);
}
function retrieveMuniCntyNames() {
var muniAndCnty;
if (req.readyState==4) {
if(req.status==200) {
var XMLresult = req.responseXML;
muniAndCnty = XMLresult.getElementsByTagName("rec");
//incoming from Servlet <twp><rec twp='Morristown town' cnty='Morris' /></twp>
var c = document.getElementById("dbCounty");
var t = document.getElementById("dbMuni")
c.setAttribute("value",muniAndCnty[0].getAttribute("cnty") )
t.setAttribute("value",muniAndCnty[0].getAttribute("municipality") )
}
}
}
</script>
Function checkGPSCoords knows a document name (which is my JSP file name).
What I puzzle me that callback function retrieveMuniCntyNames() also knows the name of the document since it sets attributes to input elements on the JSP without error.
I checked it the firebug.
I would appreciate any thoughts on the subject.
Thanks,
Chris
I'm unsure what setup you're trying to convey here, or where the javascript would be in the code. I'm making the assumption here that you've defined the script in the same page or you're including it from an external file.
Nonetheless, when the javascript executes, the browser isn't leaving the page. Therefore, the document doesn't change. From the code you've provided, you're not attempting to open a new window or navigate away from the page. Therefore the document variable hasn't changed from one function call to another, even after a successful AJAX call. It's the same document before, during, and after the AJAX call.
By that same token, you can probably eliminate the currentWindow parameter from your checkGPSCoords function. You're not really checking a window object since you're passing a document object to the function. Also, the window object doesn't have a getElementById method.

Categories