Javascript does not recognise dynamic div content - javascript

I have a script i have been battling with now for like a week.
I have a page which has a div with id ("content"). Now I loaded some content, a form contained in a div tag to be specific, into this div VIA Ajax, and it is displaying fine
Now, the challenge is - When the form is submitted, Im am calling a function that will disable all the field on the element in that div tag. I always get the error "undefined".
It seems that the div, that i brought in to the page isn't recognized by javascript..
I have searched google, bing, yahoo..i just havent found the solution yet...
Please, what do I do??
I have included the code below --
+++++++++
The code below for my external javascript file
++++++++++++++++++++
// JavaScript Document
var doc = document;
var tDiv;
var xmlHttp;
var pgTitle;
function getXMLObj(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
Obj = new XMLHttpRequest();
}
else if (window.ActiveXObject){
// code for IE6, IE5
Obj = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support Ajax!");
}
return Obj;
}
function loadCont(toLoad, view){
doc.getElementById('loadBlank').innerHTML = '<div id="loading">Processing Request...</div>';
var url;
switch(toLoad){
case 'CI':
pgTitle = "Administration - Company Information";
url = "comp_info.php?v=" + view + "&sid=" + Math.random();
break;
case 'JB':
pgTitle = "Administration - Jobs";
url = "jobs.php?v=" + view + "&sid=" + Math.random();
break;
case 'US':
pgTitle = "Administration - Users";
url = "users.php?v=" + view + "&sid=" + Math.random();
break;
case 'EP':
pgTitle = "Administration - Employees";
url = "emp.php?v=" + view + "&sid=" + Math.random();
break;
case 'AP':
pgTitle = "Administration - Recruitments";
url = "applicants.php?v=" + view + "&sid=" + Math.random();
break;
case 'JV':
pgTitle = "Administration - Recruitments";
url = "jobvacancy.php?v=" + view + "&sid=" + Math.random();
break;
}
xmlHttp = getXMLObj();
if (xmlHttp !== null && xmlHttp !== undefined){
xmlHttp.onreadystatechange = loadingContent;
xmlHttp.open('GET', url, true);
xmlHttp.send(null);
}
}
function loadingContent(){
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){
//Show the loading and the title, but hide the content...
if (xmlHttp.status == 200){
doc.getElementById('dMainContent').innerHTML = parseScript(xmlHttp.responseText);
doc.getElementById('loadBlank').innerHTML = '';
}
else{
doc.getElementById('dMainContent').innerHTML = 'Sorry..Page not available at this time. <br />Please try again later';
doc.getElementById('loadBlank').innerHTML = '';
}
}
if (xmlHttp.readyState < 4){
//Show the loading and the title, but hide the content...
doc.getElementById('ActTitle').innerHTML = pgTitle;
doc.getElementById('dMainContent').innerHTML = '';
}
}
function valCompInfo(){
//First Disable All the elements..
alert('I was hree');
DisEnaAll('CompForm');
//Now..lets validate the entries..
}
function DisEnaAll(contId){
//alert(doc.getElementById(contId).elements);
var theId = doc.getElementById(contId).elements;
try{
var numElems = theId.length;
for (var i=0; i < (numElems - 1); i++){
(theId[i].disabled == false) ? (theId[i].disabled = true) : (theId[i].disabled = false);
}
}
catch(e){
var msg = "The following error occurred: \n\n";
msg += e.description
alert(msg);
}
}
// http://www.webdeveloper.com/forum/showthread.php?t=138830
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
}
catch(ex) {
// do what you want here when a script fails
}
}
// Return the cleaned source
return source;
}
This code is on the main page where the javascript is
<div id="dMainContent">
</div>
</body>
</html>
And finally, the content of the page i am loading via ajax..
<div style="width:738px" id="CompForm">
<div class="tdright">
<?php echo $btnNm; ?>
</div>
</div>
That's the code..
Thanks

The issue is with div tag (id "CompForm") which is not a HTML form.
"elements" is a collection of the form element not div element. So when trying to access div.elements the property is undefined.
See MSDN, form.elements is part of DOM level 1 (according to MSDN)
http://msdn.microsoft.com/en-us/library/ms537449%28v=VS.85%29.aspx

Add your Javascript functions or external JS file to the original page.

this is not JavaScript....
doc.getElementById(contId).elements
but is used in your JavaScript... you will definitely not get anything. (null)
I don't think this is valid either:
theId[i].disabled == false

EDIT: Note per comments: this is NOT the answer :) See comments for details of why.
Left as an answer simply as a learning aid aid as suggested.
Shouldn't
xmlHttp.onreadystatechange = loadingContent;
be
xmlHttp.onreadystatechange = loadingContent();
or
loadingContent();
and that function should return a value if you want to assign it like that...

Related

javascript from ajax doesn't get proper execution

Using Ajax, I've created a sort of console that allows me to execute some PHP functions dynamically.
It looks like this
The problem is that after a bunch of commands, the console becomes hard to read. So I've created a javascript function, named "wipe();", which clears the <div> containing the console.
I tested this function with the developpers tools of chrome (the javascript console) and it works perfectly.
But when I try to call this function by making the PHP-AJAX return a "<script>wipe();</script>", it doesn't work. It does nothing.
I've read on the internet that all the "<script></script>" works independently from each other, but that you can call a <script>function</script> from another <script></script> block.
So why is it failing to do that ?
here is the php code :
echo '<script>wipe();</script>';
and here is the the first <script> block:
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data="+data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML+escapeHtml(data)+'<br>'+xmlhttp.responseText+'<br><br>';
}
xmlhttp.send();
}
function wipe(){
span.innerHTML = '';
}
To avoid security issues ( like a cross-site scripting attack) HTML5 specifies that a <script> tag inserted via innerHTML should not execute.
A way to execute the script is to evaluate the html using eval() . Be warned: using eval can be dangerous.
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data=" + data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML + escapeHtml(data) + '<br>' + xmlhttp.responseText + '<br><br>';
evalJSFromHtml(span.innerHTML);
}
xmlhttp.send();
}
function wipe() {
span.innerHTML = '';
}
function evalJSFromHtml(html) {
var newElement = document.createElement('div');
newElement.innerHTML = html;
var scripts = newElement.getElementsByTagName("script");
for (var i = 0; i < scripts.length; ++i) {
var script = scripts[i];
eval(script.innerHTML);
}
}
}
Call the 'wipe' function as a callback function directly from the 'send' function. Check status = 200 for a success response.
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data="+data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML+escapeHtml(data)+'<br>'+xmlhttp.responseText+'<br><br>';
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
wipe(); // 'Wipe' callback function
}
}
xmlhttp.send();
}
function wipe(){
span.innerHTML = '';
}
But when I try to call this function by making the PHP-AJAX return a "wipe();", it doesn't work. It does nothing.
try create script tag and add to document rather than change inner html.
var spaScript = document.getElementById("spaScript");
var wraper = document.createElement("div");
wraper.innerHTML = xmlhttp.responseText;
var script = document.createElement("script");
script.innerHTML = wraper.getElementsByTagName("script")[0].innerHTML;
spaScript.appendChild(script);
Test if wipe() is in the input and if it is trigger it instead of the ajax call
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
if (data.indexOf('wipe()') == -1) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data=" + data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML + escapeHtml(data) + '<br>' + xmlhttp.responseText + '<br><br>';
}
xmlhttp.send();
}
} else {
wipe();
};
}
function wipe() {
span.innerHTML = '';
}
inserting a script tag directly inside an element should not work (and by the way generating an error in the console).
Using the native eval() function on the response text without speciying the tag attribute should solve the problem.
on server side
echo 'wipe()';
on client side
eval(xmlhttp.responseText)

Parsing information about the latest GitHub commit

I've been trying to retrieve information about the latest commit of a specific repo using Javascript, but without many results.
I've been using a XMLHttpRequest to get the data from the repo's commits page (for example: https://api.github.com/repos/trapped/rotmg_svr/commits), but seems like it returns null.
Also, I tried to use regular expressions to get the first match of specific line values (for example, to get the value of the commit description, I used this one: "message": "(.*)", ), making it loop through all lines until it finds something (in the code I've posted I temporarily changed it to line numbers, trying to speed up the process since it wasn't working).
Also, when trying to load the page, it blocks. As my previous experience with C#'s webclient suggests me, it's probably related to the XMLHttpRequest thing (indeed when I tried to debug it was returning an undefined object).
Thanks in advance for all the help.
var messagelineindex = 14;
var linklineindex = 17;
var response = "";
function loadcommits() {
httpGet("https://api.github.com/repos/trapped/rotmg_svr/commits");
var lines = response.split("\n");
var message = parsemessage(lines[messagelineindex]);
var link = parselink(lines[linklineindex]);
addcommit(//+message+"");
//for (var i = 0; i < numlines; i++) {
// var line = lines[i];
// var commitmessage = parsemessage(line);
// if (commitmessage != "") {
// addcommit(commitmessage);
// break;
// }
//}
}
function parselink(text) {
var regex = /"link": "(.*)",/;
var match = regex.exec(text);
if (!match) {
return "";
}
else {
return match[1];
}
}
function parsemessage(text) {
var regex = /"message": "(.*)",/;
var match = regex.exec(text);
if (!match) {
return "";
}
else {
return match[1];
}
}
function addcommit(text) {
document.getElementById("commits").innerHTML = document.getElementById("commits").innerHTML + text.toString() + "\n\r";
}
function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
response = xmlHttp.responseText;
}
}
xmlHttp.open("GET", theUrl, false);
xmlHttp.send(null);
}

Slow ajax for simple DB access

While testing out setInterval(), i had a slow load time for an ajax request. It was very simple and other pages with much more complex requests were terminating in less than a second while this very simple one is terminating after 10-12. Without using setInterval() it is still taking this long and it uses the same layout as the other pages.
Example of script:
document.getElementById("test").innerHTML = "Starting";
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("test").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/TestLive.cshtml", true);
xmlhttp.send();
Slow server page (ASP.NET):
Response.Expires = -1;
var db = Database.Open("mydb");
string query = "select Name from Game where ID='97';";
Response.Write(db.QuerySingle(query).Name);
Example of fast:
Response.Expires = -1;
string query = "select * from Season where Season.Game = 'Football' and Season.End > '" + DateTime.Now.Add(new TimeSpan(-8,0,0)).ToString("yyyy-MM-dd") + "';";
var db = Database.Open("mydb");
var result = db.Query(query);
Response.Write("<select id=\"chosenSeason\" onchange=\"setDraftSeason()\">");
Response.Write("<option selected=\"selected\">Choose a Season</option>");
foreach (var season in result)
{
Response.Write("<option value=\"" + season.ID + "\">");
Response.Write(season.Name);
Response.Write(" (" + season.Start.ToString("dd-MM-yyyy") + " - " + season.End.ToString("dd-MM-yyyy") + ")");
Response.Write("</option\">");
}
Response.Write("</select>");
EDIT: It seems to be related to using the layout page to access the script. all of the fast pages use the same setup though.

JavaScript: "Syntax error missing } after function body"

Ok, so you know the error, but why on earth am I getting it?
I get no errors at all when this is run locally, but when I uploaded my project I got this annoying syntax error. I've checked the Firebug error console, which doesn't help, because it put all my source on the same line, and I've parsed it through Lint which didn't seem to find the problem either - I just ended up formatting my braces differently in a way that I hate; on the same line as the statement, bleugh.
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}
}
function Login() {
// Grab username and password for login
var uName = document.getElementById('uNameBox').value;
var pWord = document.getElementById('pWordBox').value;
ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);
}
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}
function Chat() {
// Get username from recipient box
var user = document.getElementById('recipient').value;
self.location = 'index.php?to=' + user;
}
function SendMessage() {
// Grab message from text box
var from = readCookie('privateChat');
var to = getUrlVars()['to'];
var msg = document.getElementById('msgBox').value;
ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg);
// Reset the input box
document.getElementById('msgBox').value = "";
}
function GetMessages() {
// Grab account hash from auth cookie
var aHash = readCookie('privateChat');
var to = getUrlVars()['to'];
ToServer('cmd=pop','&account=' + aHash + '&to=' + to);
var textArea = document.getElementById('messages');
textArea.scrollTop = textArea.scrollHeight;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
The problem is your script on your server is in one line, and you have comments in it. The code after // will be considered as comment. That's the reason.
function ToServer(cmd, data) { var xmlObj = new XMLHttpRequest(); xmlObj.open('POST', 'handler.php', true); xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xmlObj.send(cmd + data); xmlObj.onreadystatechange = function() { if(xmlObj.readyState === 4 && xmlObj.status === 200) { if(cmd == 'cmd=push') { document.getElementById('pushResponse').innerHTML = xmlObj.responseText; } if(cmd == 'cmd=pop') { document.getElementById('messages').innerHTML += xmlObj.responseText; } if(cmd == 'cmd=login') { if(xmlObj.responseText == 'OK') { self.location = 'index.php'; } else { document.getElementById('response').innerHTML = xmlObj.responseText; } } } };}function Login() { // Grab username and password for login var uName = document.getElementById('uNameBox').value; var pWord = document.getElementById('pWordBox').value; ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);}// Start checking of messages every secondwindow.onload = function() { if(getUrlVars()['to'] != null) { setInterval(GetMessages(), 1000); }}function Chat() { // Get username from recipient box var user = document.getElementById('recipient').value; self.location = 'index.php?to=' + user;}function SendMessage() { // Grab message from text box var from = readCookie('privateChat'); var to = getUrlVars()['to']; var msg = document.getElementById('msgBox').value; ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg); // Reset the input box document.getElementById('msgBox').value = "";}function GetMessages() { // Grab account hash from auth cookie var aHash = readCookie('privateChat'); var to = getUrlVars()['to']; ToServer('cmd=pop','&account=' + aHash + '&to=' + to); var textArea = document.getElementById('messages'); textArea.scrollTop = textArea.scrollHeight;}function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null;}function getUrlVars() { var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); return vars;}
You're missing a semi-colon:
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}; //<-- Love the semi
}
Additional missing semi-colon:
// Start checking of messages every second
window.onload = function() {
if (getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; //<-- Love this semi too!
I think you can adapt divide and conquer methodology here. Remove last half of your script and see whether the error is coming. If not, remove the first portion and see. This is a technique which I follow when I get an issue like this. Once you find the half with the error then subdivide that half further till you pin point the location of the error.
This will help us to identify the actual point of error.
I do not see any problem with this script.
This may not be the exact solution you want, but it is a way to locate and fix your problem.
It looks like it's being interpreted as being all on one line. See the same results in Fiddler 2.
This problem could do due to your JavaScript code having comments being minified. If so and you want to keep your comments, then try changing your comments - for example, from this:
// Reset the input box
...to...
/* Reset the input box */
Adding a note: very strangely this error was there very randomly, with everything working fine.
Syntax error missing } after function body | At line 0 of index.html
It appears that I use /**/ and //🜛 with some fancy Unicode character in different parts of my scripts for different comments.
This is useful to me, for clarity and for parsing.
But if this Unicode character and probably some others are used on a JavaScript file in comments before any JavaScript execution, the error was spawning randomly.
This might be linked to the fact that JavaScript files aren't UTF-8 before being called and read by the parent page. It is UTF-8 when the DOM is ready. I can't tell.
It seems there should be added another semicolon in the following code too:
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; <---- Semicolon added
Also here in this code, define the var top of the function
function readCookie(name) {
var i;
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
"Hm I think I found a clue... I'm using Notepad++ and have until recently used my cPanel file manager to upload my files. Everything was fine until I used FireZilla FTP client. I'm assuming the FTP client is changing the format or encoding of my JS and PHP files. – "
I believe this was your problem (you probably solved it already). I just tried a different FTP client after running into this stupid bug, and it worked flawlessly. I'm assuming the code I used (which was written by a different developer) also is not closing the comments correctly as well.

Can I focus a dynamically loaded AJAX element?

My scenario is that I have a form on my page. My client would like to be able to fill out the form completely without ever touching the mouse. The problem is that I have a sort of "auto-complete" function that searches our DB (via AJAX) for similar entries, and dynamically loads them into a select element. Then you are able to click the entry that you'd like to have "auto-complete" the form.
To please my client, I am trying to find a way to have that dynamic select element acquire focus once it is loaded, so that the user can press the arrow keys and enter to select what they want, without using the mouse.
After googling for solutions, I have tried adding
document.getElementById('ajaxbox').focus();
into the function called when onreadystatechange is triggered. I have also tried adding that line as a script, and write the script in when the select box is written to the page. Neither of these have worked (either for reasons I can't determine or because I get the error that ajaxbox is null, telling me that it's trying to call the focus() before the box is loaded on the page).
Any ideas? I can provide further information, but not a functioning sample page. Javascript or JQuery solutions are preferred.
EDIT:
Added some code. The URL referenced in the first function is to a java servlet that writes the dynamic html onto the page (via a print writer). I can't really change that currently (due to time constraints). This is all inherited code, so please let me know if there are things that could/should change. I won't be offended.
Here is a portion of the javascript where I was trying to set the focus.
function xmlreqGET(url) {
//alert('ajax');
var xmlhttp=false;
var xmlreq;
try {
if (window.XMLHttpRequest) { // Mozilla, etc.
xmlhttp=new XMLHttpRequest();
xmlreq = new CXMLReq('', xmlhttp);
xmlreqs.push(xmlreq);
urlAr.push(url);
xmlhttp.onreadystatechange = xmlhttpChange;
//alert(url);
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
} else if (window.ActiveXObject) { // IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp) {
xmlreq = new CXMLReq('', xmlhttp);
xmlreqs.push(xmlreq);
xmlhttp.onreadystatechange = xmlhttpChange;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
} catch (e) { }
}
function xmlhttpChange() {
if (typeof(window['xmlreqs']) == "undefined") {
return;
}
try {
if (window.ActiveXObject) { // IE
for (var i=0; i < xmlreqs.length; i++) {
if (xmlreqs[i].xmlhttp.readyState == 4) {
if (xmlreqs[i].xmlhttp.status == 200 || xmlreqs[i].xmlhttp.status == 304) {
// 200 OK
// get response info here before splicing - see below on creating an xml object
var response = xmlreqs[i].xmlhttp.responseText;
//alert(name + ' ' + response);
if (name != "assignCase")
document.getElementById(div_id).style.top = 15;
document.getElementById(div_id).style.left = 50;
if (name == "streetName" || name == "equipName")
document.getElementById(div_id).style.top = 400;
document.getElementById(div_id).style.left = 50;
if (name == "equipment" ) {
document.getElementById(div_id).style.top = 150;
document.getElementById(div_id).style.left = 475;
}
document.getElementById(div_id).innerHTML = response;
xmlreqs.splice(i,1); i--;
urlAr.splice(i,1); i--;
} else {
xmlreqs.splice(i,1); i--;
urlAr.splice(i,1); i--;
}
}
}
} else {
//alert('at else');
for (var i=0; i < xmlreqs.length; i++) {
//alert(i + ':' + name + ':' + xmlreqs.length);
if (xmlreqs[i].xmlhttp.readyState == 4) {
if (xmlreqs[i].xmlhttp.status == 200 || xmlreqs[i].xmlhttp.status == 304) {
// 200 OK
// get response info here before splicing - see below on creating an xml object
// alert('200 was here' + name);
var response = xmlreqs[i].xmlhttp.responseText;
var len = response.length;
if (name == "streetName" || name == "equipName" || name == "city" || name == "zip" || name == "grid") {
document.getElementById(div_id).style.top = 270;
document.getElementById(div_id).style.left = 50;
} else if (name == "upstream"){
document.getElementById(div_id).style.left = 600;
document.getElementById(div_id).style.top = 150;
} else if (name == "equipment" ) {
document.getElementById(div_id).style.top = 125;
document.getElementById(div_id).style.left = 500;
} else if (name == "pingMeter"){
document.getElementById(div_id).style.left = 1025;
document.getElementById(div_id).style.top = 210;
} else if (name == "assignCase") {
//document.getElementById(div_id).style.top = 60;
//document.getElementById(div_id).style.left = 120;
} else {
document.getElementById(div_id).style.top = 400;
document.getElementById(div_id).style.left = 50;
}
document.getElementById(div_id).innerHTML = response;
if (response == "") {
// xmlreqGET(urlAr[i]);
xmlreqs.splice(i,1); i--;
urlAr.splice(i,1); i--;
} else {
//document.getElementById(div_id).innerHTML = response;
xmlreqs.splice(i,1); i--;
urlAr.splice(i,1); i--;
}
}
}
if (xmlreqs[i].xmlhttp.readyState < 4) {
// confirm('at nloading');
document.getElementById(div_id).style.top = 270;
document.getElementById(div_id).style.left = 50;
document.getElementById(div_id).innerHTML = "<div align=center class='fixedwidth' style='background-color:#ffff8f'> <br> <img src='omscontrol/common/images/loading.gif' width='20'><Font size=1> Loading Content....Please Wait! </Font><br> </div>";
}
}
}
alert(document.getElementById('firstOption'));
document.getElementById('firstOption').focus();
} catch (e) { }
}
Example from the servlet as to how the HTML is being written. This isn't really something I want to get into changing at this time.
comboOption = new StringBuffer();
/* Version 1.0.2 */
comboOption.append("<select id=\"" + id + "\" class='fixedwidth' style=\'background-color:#ffff8f\' size='4' "
+ "onchange=\"popVal(this.options[this.selectedIndex].value); populateValues('" + id + "');\">");
comboOption.append("<option value=''>" + "No Matches Found!" + "</option>");
/* Version 1.0.2 */
comboOption.append("</select>");
out.print(comboOption.toString());
I had tried adding the focus() to a script, and putting it into that last append. I'm not sure if that is even something that could work, but it didn't for me.
EDIT 2:
I added document.getElementById('firstOption').focus(); to the very end of the two readyState == 4 if conditions. I can tell that the element does exist at that time, but my focus actually ends on nothing. (I found that out by adding
$(document.activeElement).change(function(){
alert("NEWFOCUS: " + document.activeElement.id);
});
to my JSP. If that isn't reliable, please tell me.)
you have to append the input element first to the DOM before you call the focus function
var div = document.getElementById("dynamic");
$.ajax({
...
success:function (data) {
// append the new created input to the DOM
....
div.appendChild(newInput);
newInput.focus();
}
});
You are probably trying to access ajaxbox before it is present in the DOM that's why you are getting a null

Categories