JavaScript - String.length Function Returns Undefined
Hello,
When I run the following code, the .Length function returns "undefined." Please help! This is driving me crazy. Code: var strTest = 'test'; alert(strTest.Length); Using the typeof function, I know that JS is treating the variable as a string. Any suggestions? Similar Tutorialshi here is a code i use to calculate distance b//w 2 places using google api... it works perfectly and shows the results in the html but when i add a return statement at the end of the function showlocation() it returns undefined.. why it is so.. how to resolve it??? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <meta name="robots" content="noindex,follow" /> <title>Calculate driving distance with Google Maps API</title> <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAMK3PClIOG6IUkYprx4EfNxSY_HQRLXr6AGORx7Qh39w3-je8JxRROt5eJTcDPJ9nGnVn9xXKTQ2l8Q" type="text/javascript"></script> <!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html --> <script type="text/javascript"> var geocoder, location1,addr1,addr2, location2, result1,gDir; function coolAl(add1,add2) { addr1=add1; addr2=add2; var result= return initialize(); showLocation(); alert(result); } function initialize() { geocoder = new GClientGeocoder(); gDir = new GDirections(); GEvent.addListener(gDir, "load", function() { var drivingDistanceMiles = gDir.getDistance().meters / 1609.344; var drivingDistanceKilometers = gDir.getDistance().meters / 1000; result1=location1.address + ' (' + location1.lat + ':' + location1.lon + ')/' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')/' + drivingDistanceKilometers + ' kilometers'; document.body.innerHTML=result1; return drivingDistanceKilometers; }); } function showLocation() { geocoder.getLocations(addr1, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the first address"); } else { location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; geocoder.getLocations(addr2, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the second address"); } else { location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; gDir.load('from: ' + location1.address + ' to: ' + location2.address); } }); } }); } </script> </head> <body onload="coolAl('pune','mumbai')"> </html> Suppose we have following javascript codes: Case 1. var foo = function () { var x = "hello"; var bar = function () { alert(x); } return bar; } var bar_ref= foo(); document.write(bar_ref()); // it pops up "hello" and print-outs "undefined". If we modified above code slightly, shown as follow: Case 2. var foo = function () { var x = "hello"; var bar = function () { alert(x); } return bar(); } var bar_ref= foo(); document.write(bar_ref()); // it only pops up "hello". As you can see, Case 2 modified the return value from "return bar" to "return bar()," which won't cause the "undefined" output. To me, it looks like when the JS interpreter executes the line "bar_ref();" it triggers the execution of function "foo", besides both "return bar" and "return bar()" do the same job which is to execute function body of "bar". The only difference is that after the execution of function bar, its function body does not exist anymore, so when the interpreter executes the line "return bar;" it follows the function identifier "bar" and ends up with "undefined". This is why the Case 1 gives us "undefined", but I am not quite clear about why the Case 2 can trace down to the function body of "bar". Do you have any ideas about such difference outputs? Dan How can I call a function in javascript like: Code: var x = string.Length ??? and not like: Code: var x = Length(string); (just for arguments sake) (Also please don't suggest JQuery, I'm doing this to learn!) Thanks! Hi, I started getting a wierd problem with my jscript program. Here im using jscript for client-side validation and upon email field submission,im getting undefined value with an error saying "length is null or not an object". All the values of fields prior to that are being obtained properly. Please help me out of this crisis AJAX XMLHttpRequest responseText returns undefined but alert returns expected text. Code: function getFile(fileToOpen) { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } else { alert("Your browser does not support XMLHTTP!"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState==4) { //alert(xmlhttp.responseText); return xmlhttp.responseText; } } xmlhttp.open("GET",fileToOpen,true); xmlhttp.send(null); } Code: document.getElementById('widgetOptionsShadow').innerHTML = '<div id="widgetOptions">' + getFile('/togglePauseInit.php?g=<?php echo $gadgetName; ?>') + '</div>'; I have a string of text, and starting from a particular spot (known to be a number), I want to find the length of that number. Here's what I have: Code: ... var start = [...predetermined...] var end = 0; while (!isNaN(sourceCode.charAt(start + end))){ endCurrent++; } var myNum = sourceCode.substr(start, end) * 1; So let's say var sourceCode = "alkdjabjasdsdf-53 dnalsdb..."; , startCurrent will already be at the "5" and I want to be able to extract the "53". What I have works, but it seems cumbersome... Any advice? Code: <script> // Declared Constants MORSE_ALPHABET = new Array ( '.-', // A '-...', // B '-.-.', // C '-..', // D '.', // E '..-.', // F '--.', // G '....', // H '..', // I '.---', // J '-.-', // K '.-..', // L '--', // M '-.', // N '---', // O '.--.', // P '--.-', // Q '.-.', // R '...', // S '-', // T '..-', // U '...-', // V '.--', // W '-..-', // X '-.--', // Y '--..' // Z ); CHAR_CODE_A = 65; var CTS = prompt('Enter Morse code','here') var inMessage = CTS.split(' '); searchLocation(inMessage,MORSE_ALPHABET) function searchLocation(targetValue, arrayToSearchIn) { var searchIndex = 0; // Iterative counter for(i=0;i < targetValue.length;) { targetValue = targetValue[i]; // Search until found or end of array while( searchIndex<arrayToSearchIn.length && i != targetValue.length && arrayToSearchIn[searchIndex]!=targetValue ) { i++ searchIndex++; } if(searchIndex<arrayToSearchIn.length) { return String.fromCharCode(CHAR_CODE_A + searchIndex); } else { return -1; } } } document.writeln(searchLocation(inMessage,MORSE_ALPHABET)); </script> <head> </head> <body> </body> This is my code and i have figured it to create an array from the prompt and then use the function to return the first array it finds but i cant seem to make it go on to the next index of the array. I know that when you return a value the function closes and i have tried to store my return in a variable but its not working the way i want it to or I'm not writing the correct command or is there away to do multiply returns, i think what i need to do is simply but i have been staring at this screen for a while now and just cant see it. Please help me. Thanks i keep getting error Call to undefined function codeandurl() below is my code PHP Code: <?php $value= strip_tags(get_field('link',$post)); $resultid=get_field('resultid',$post); codeandurl($resultid,$value); ?> <div id="result"></div> <script type="text/javascript"> function codeandurl(resultid,url){ $( "#result" ).text(resultid); $( "#result" ).dialog({ modal: true, buttons: { Ok: function() { $( this ).dialog( "close" ); } } }); window.open(url); return false; } </script> My array is like so... shp[0][0] = 5; shp[0][1] = "A5"; shp[0][2] = "A2"; shp[0][3] = "A1"; shp[0][4] = "A4"; shp[0][5] = "A3"; shp[1][0] = 4; shp[1][1] = "C3"; shp[1][2] = "C4"; shp[1][3] = "C1"; shp[1][4] = "C2"; shp[2][0] = 3; shp[2][1] = "E1"; shp[2][2] = "E3"; shp[2][3] = "E2"; shp[3][0] = 3; shp[3][1] = "G3"; shp[3][2] = "G2"; shp[3][3] = "G1"; shp[4][0] = 2; shp[4][1] = "I2"; shp[4][2] = "I1"; the results I am after is... shp[0][0] = 5; shp[0][1] = "A1"; shp[0][2] = "A2"; shp[0][3] = "A3"; shp[0][4] = "A4"; shp[0][5] = "A5"; shp[1][0] = 4; shp[1][1] = "C1"; shp[1][2] = "C2"; shp[1][3] = "C3"; shp[1][4] = "C4"; shp[2][0] = 3; shp[2][1] = "E1"; shp[2][2] = "E2"; shp[2][3] = "E3"; shp[3][0] = 3; shp[3][1] = "G1"; shp[3][2] = "G2"; shp[3][3] = "G3"; shp[4][0] = 2; shp[4][1] = "I1"; shp[4][2] = "I2"; so it sorts all from the second part of the array to the end in alpha-numerical order. I tried the following but i get errors about Cannot call method 'unshift' of undefined. // var shp; var shpbk; var shpbktemp; // shpbk = shp.slice(); shpbktemp[0] = shpbk[0][0]; shpbk[0] = shpbk[0].shift; shpbk[0] = shpbk[0].sort; shpbk[0] = shpbk[0].unshift(shpbktemp[0]); shpbktemp[1] = shpbk[1][0]; shpbk[1] = shpbk[1].shift; shpbk[1] = shpbk[1].sort; shpbk[1] = shpbk[1].unshift(shpbktemp[1]); shpbktemp[2] = shpbk[2][0]; shpbk[2] = shpbk[2].shift; shpbk[2] = shpbk[2].sort; shpbk[2] = shpbk[2].unshift(shpbktemp[2]); shpbktemp[3] = shpbk[3][0]; shpbk[3] = shpbk[3].shift; shpbk[3] = shpbk[3].sort; shpbk[3] = shpbk[3].unshift(shpbktemp[3]); shpbktemp[4] = shpbk[4][0]; shpbk[4] = shpbk[4].shift; shpbk[4] = shpbk[4].sort; shpbk[4] = shpbk[4].unshift(shpbktemp[4]); Hi, so I have this function: Code: function centerZoom() { var bounds = new google.maps.LatLngBounds(); for (var i = 0; i < gmarkers.length; i++) { if (!gmarkers[i].isHidden()) { var point = gmarkers[i].getPoint(); bounds.extend(point); } map.setZoom(map.getBoundsZoomLevel(bounds)); map.setCenter(bounds.getCenter()); } } which I call he Code: for (var j = 0; j < gmarkers.length; j++) { var str=gmarkers[j].myname.toLowerCase(); var patt1=inp; if (str.match(patt1)) { found = true; gmarkers[j].show(); centerZoom(); } which I thought was pretty straightforward, but I keep getting a "centerZoom is undefined" message. The only place I don't get that is if I take it out of the initialize sequence, but it doesn't work then anyway (and from what I understand, being that it contains var bounds = new... it has to go in initialize. Here's the rest of the page, if anybody has any ideas New to javascript, so I'm trying to work through a rather older, but helpful nonetheless book entitled "Head Rush Ajax". I'm only finishing up the first chapter...lol and my code is not doing what its supposed to be doing. I'm sure its something simple like a typo, but I have been over it several times and cant spot the problem. When I try to run the script in IE8, it throws an error saying object expected. line 43 code 0 Here is my complete script. According to the book I should be able to click the button and the values will update only once. PHP Code: var request = null; function createRequest() { try { request = new XMLHttpRequest(); } catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = null; } } } if (request == null) alert("Error creating request object!"); } function getBoardsSold() { createRequest(); var url="getUpdatedBoardSales-ajax.php"; request.open("GET", url, true); request.onreadystatechange = updatePage; request.send(null); } function updatePage() { if (request.readyState == 4) { var newTotal = request.responseText; var boardsSoldEl = document.getElementById("boards-sold"); var cashEl = document.getElementById("cash"); replaceText(boardsSoldEl, newTotal); // Figure out how much cash katie has made var priceEl = document.getElementById("price"); var price = getText(priceEl); var costEl = document.getElementById("cost"); var cost = getText(costEl); var cashPerBoard = price - cost; var cash = cashPerBoard * newTotal; //update the cash for the slopes on the form cash = Math.round(cash * 100) / 100; replaceText(cashEl, cash); } } Thanks for any help in advance! Hi.. I encountered problem in using $_GET to get the DATE_PROCESS. here is my code: Code: <script> function editloan(){ var dateprocess = document.getElementById('dateprocess').value; alert(dateprocess); window.location = "SSSLoan.php?dateprocess="+dateprocess; } </script> Code: <div id="searchname"> <form> <p class="serif"><b>Search Lastname:</b></p> <input type="text" name="ssssearch" size="20" onkeyup="fetchsuggest(this.value);"> <div> <hr /> <ul id="suggest" style="overflow:auto; height:380px; width:auto;"> {section name=co_emp loop=$personalAll} <li><a href="SSSgetdata.php?queryEmpID={$personalAll[co_emp].EMP_ID}">{$personalAll[co_emp].FULLNAME}</a></li> <hr /> {sectionelse} <li>No records found</li> {/section} </ul> </div> </div> <div id="loanformmain"> <input type="button" name="sssbtn" value="SSS" onclick="loanFrm()"> <input type="button" name="hdmfbtn" value="HDMF" onClick="hdmfloanFrm()"> <input type="button" name="UTbtn" value="Union Dues/Trust Fund" onclick="utloanFrm()"> </div> <div id="sssloan"> <fieldset> <legend>SSS Loan</legend> <p class="serif"> <label id="SSSLabel">SSS ID</label><label id="EMPIDLabel">EMP ID</label><label id="NAMELabel">NAME</label><label id="LOANLabel">LOAN</label><label id="AMORLabel">DEDUCTION</label> <input type="text" name="SSS" value="{$sss}" size="8" style="background: #e2e2e2" readonly="readonly"> <input type="text" name="EMP_NO" value="{$empno}" size="8" style="background: #e2e2e2" readonly="readonly"> <input type="text" name="NAME" value="{$fullname}" style="background: #e2e2e2" readonly="readonly" size="35"> <input type="text" name="LOAN" value="{$LOAN}" size="9"> <input type="text" name="AMOR" value="{$AMOR}" size="9"> <input type="button" name="add" value="ADD" onclick="SSSAdd()"> <input type="hidden" name="dateprocess" value="{$dateprocess"> </p> </legend> </fieldset> <div style="overflow:auto; height:300px; width:auto;"> <p> <table border="1" class="stat"> <tr> <td colspan="4" style="text-align:center">SSS ID</td> <td colspan="4" style="text-align:center">EMP ID</td> <td colspan="15" style="text-align:center">NAME</td> <td colspan="4" style="text-align:center">LOAN</td> <td colspan="4" style="text-align:center">DEDUCTION</td> <td colspan="4" style="text-align:center">DATE PROCESS</td> </tr> {section name=att loop=$getsss} <tr> <td colspan="4" style="background: #e2e2e2" readonly="readonly">{$getsss[att].SSS}</td> <td colspan="4" style="background: #e2e2e2" readonly="readonly">{$getsss[att].EMP_NO}</td> <td colspan="15" style="background: #e2e2e2" readonly="readonly">{$getsss[att].FULLNAME}</td> <td colspan="4" style="background: #e2e2e2" readonly="readonly">{$getsss[att].SSSLoan}</td> <td colspan="4" style="background: #e2e2e2" readonly="readonly">{$getsss[att].SSSAmor}</td> <td colspan="4" style="background: #e2e2e2" readonly="readonly" id="dateprocess" onclick="editloan('{$getsss[att].DATE_PROCESS}')">{$getsss[att].DATE_PROCESS}</td> </tr> {sectionelse} <tr><td colspan="1">No DATA</td></tr> {/section} </table> <table border="1"> <tr> <td colspan="4" style="text-align:center"><b>TOTAL:</b></td> <td colspan="5" style="background: #e2e2e2" readonly="readonly">{$Total_Loan}</td> </tr> </table> </p> </form> </div> </div> Code: <?php include 'config.php'; $currentEmpID = $_SESSION['empID']; $sql = "SELECT EMP_ID, CONCAT(LNAME, ', ', FNAME, ' ', MI, '.') AS FULLNAME, SSS, HDMF, TIN FROM PERSONAL WHERE EMP_ID='$currentEmpID'"; $recPersonal = $conn->Execute($sql); if (!$recPersonal) { print $conn->ErrorMsg(); } if (!$recPersonal->BOF) { $recPersonal->MoveFirst(); } $sss = trim($recPersonal->fields['SSS']); $hdmf = trim($recPersonal->fields['HDMF']); $tin = trim($recPersonal->fields['TIN']); $smarty->assign('sss', $sss); $sql = "SELECT EMP_ID, CONCAT(LNAME, ', ' , FNAME, ' ', MI) AS FULLNAME FROM PERSONAL ORDER BY LNAME ASC"; $recPersonalNav = $conn->GetAll($sql); $smarty->assign('personalAll', $recPersonalNav); // ======================================================================================================================== $sql = "SELECT em.EMP_NO, p.EMP_ID, CONCAT(LNAME, ', ', FNAME, ' ', MI, '.') AS FULLNAME FROM PERSONAL p, EMPLOYMENT em WHERE p.EMP_ID='$currentEmpID' AND em.EMP_ID = '$currentEmpID'"; $recPersonalHead = $conn->Execute($sql); $fullName = $recPersonalHead->fields["FULLNAME"]; $empno = $recPersonalHead->fields["EMP_NO"]; $smarty->assign('empid', $currentEmpID); $smarty->assign('fullname', $fullName); $smarty->assign('empno', $empno); //===============================SELECT SSSLoan=================================== $dateprocess = $_GET['dateprocess']; $sql = "SELECT s.EMP_NO, s.SSSLoan, s.SSSAmor, s.DATE_PROCESS FROM $PAYROLL.sssloan s, $ADODB_DB.employment em WHERE em.EMP_NO= s.EMP_NO AND s.DATE_PROCESS = '$dateprocess'"; $rsloan = $conn2->Execute($sql); $LOAN = trim($rsloan->fields['SSSLoan']); $AMOR = trim($rsloan->fields['SSSAmor']); $dateprocess = $rsloan->fields['DATE_PROCESS'] ; $smarty->assign('LOAN', $LOAN); $smarty->assign('AMOR', $AMOR); $smarty->assign('dateprocess', $dateprocess); //============================SELECT ALL DATA FOR SSSLOAN========================== $sql = "SELECT s.EMP_NO, em.EMP_ID, p.SSS, CONCAT(LNAME, ', ', FNAME, ' ', MI, '.') AS FULLNAME, s.SSSLoan, s.SSSAmor, s.DATE_PROCESS FROM $ADODB_DB.PERSONAL p, $ADODB_DB.employment em, $PAYROLL.sssloan s WHERE s.EMP_NO = em.EMP_NO AND p.EMP_ID = '$currentEmpID' AND em.EMP_ID = '$currentEmpID'"; $rs = $conn2->GetAll($sql); $smarty->assign('getsss', $rs); $sql = "SELECT s.EMP_NO, SUM(SSSAmor) AS Total_Loan FROM $PAYROLL.sssloan s, $ADODB_DB.employment em WHERE em.EMP_NO = s.EMP_NO AND em.EMP_ID = '$currentEmpID'" or die (mysql_error()); $rsTotal = $conn2->Execute($sql); $Total_Loan = $rsTotal->fields['Total_Loan']; $smarty->assign('Total_Loan', $Total_Loan); $smarty->display('header.tpl'); $smarty->display('loanForm.tpl'); $smarty->display('footer.tpl'); exit(); ?> when I click date in <td colspan="4" style="background: #e2e2e2" readonly="readonly" id="dateprocess" onclick="editloan('{$getsss[att].DATE_PROCESS}')">{$getsss[att].DATE_PROCESS}</td> it result no value...it did not get the value that I click Thank you in advance ok im having a bit of problem with this. code : <input type="hidden" value="&nsbp;" name="b1r1c1"> (insde a table} <td></script>function ba1r1c1() { document.write(b1r1c1.value); }</script></td> (later on) <script> ba1r1c1(); </script> Whats happening is its not writing the space inside the cell but somewhere else on the page but i dont know why. The table is inside <div> tags if that helps. any help apreciated. Thanks Hello, I'm hoping someone can help me with this. I have 3 pages that I need to put into my framework, they are products, shopping cart and billing. At the moment they work perfectly fine. Here is a live example - http://www.cems.uwe.ac.uk/~r4-george...g/products.php Now, I have a framework for a whole website that I need to put these pages into. (http://www.cems.uwe.ac.uk/~r4-george/wp4/index.php) The index uses a switch statement to go between pages. Here is the index.php PHP Code: <?php # index.php /* * This is the main page. * This page includes the configuration file, * the templates, and any content-specific modules. */ // Require the configuration file before any PHP code: require_once ('./modules/config.inc.php'); // Validate what page to show: if (isset($_GET['p'])) { $p = $_GET['p']; } elseif (isset($_POST['p'])) { // Forms $p = $_POST['p']; } else { $p = NULL; } // Determine what page to display: switch ($p) { case 'about': $page = 'about.inc.php'; $page_title = 'About This Site Again'; break; case 'products': $page = 'products.inc.php'; $page_title = 'Products on this site'; break; case 'this': $page = 'this.inc.php'; $page_title = 'This is Another Page.'; break; case 'that': $page = 'that.inc.php'; $page_title = 'That is Also a Page.'; break; case 'contact': $page = 'contact.inc.php'; $page_title = 'Contact Us'; break; case 'search': $page = 'search.inc.php'; $page_title = 'Search Results'; break; // Default is to include the main page. default: $page = 'main.inc.php'; $page_title = 'Site Home Page'; break; } // End of main switch. // Make sure the file exists: if (!file_exists('./modules/' . $page)) { $page = 'main.inc.php'; $page_title = 'Site Home Page'; } // Include the header file: include_once ('./includes/header.inc'); echo "<div id=\"content\">"; // Include the content-specific module: // $page is determined from the above switch. include ('./modules/' . $page); // Include the footer file to complete the template: include_once ('./includes/footer.inc'); ?> It uses the .inc.php files located in the modules folder to switch between pages. Here is my products.inc.php - PHP Code: <? include("includes/db.php"); include("includes/functions.php"); if($_REQUEST['command']=='add' && $_REQUEST['productid']>0){ $pid=$_REQUEST['productid']; addtocart($pid,1); header("location:shoppingcart.php"); exit(); } ?> <!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>Products</title> <script language="javascript"> function addtocart(pid){ document.form1.productid.value=pid; document.form1.command.value='add'; document.form1.submit(); } </script> </head> <body> <form name="form1"> <input type="hidden" name="productid" /> <input type="hidden" name="command" /> </form> <div align="center"> <h1 align="center">Products</h1> <table border="0" cellpadding="2px" width="600px"> <? $result=mysql_query("select * from products"); while($row=mysql_fetch_array($result)){ ?> <tr> <td><img src="<?=$row['picture']?>" /></td> <td> <b><?=$row['name']?></b><br /> <?=$row['description']?><br /> Price:<big style="color:green"> £<?=$row['price']?></big><br /><br /> <input type="button" value="Add to Cart" onclick="addtocart(<?=$row['serial']?>)" /> </td> </tr> <tr><td colspan="2"><hr size="1" /></td> <? } ?> </table> </div> </body> </html> This is EXACTLY the same code as the working example. The products get listed correctly but the problem I have is the 'Add to Cart' button fails to work. Live example - http://www.cems.uwe.ac.uk/~r4-george...php?p=products Everything is in the right directory. When I inspect the 'Add to Cart' button in chrome I get the following - Quote: Uncaught TypeError: Cannot set property 'value' of undefined addtocart index.php:51 (anonymous function)index.php:83 onclick Any help is really appreciated, I'm struggling to see what I have done wrong. I don't know whether it's a Javascript problem. If you need any of the code from other pages I can post it too. Thanks in advance. The following coding works in Konqueror 3.5.10 on Ubuntu 8.04.3 LTS but not on Firefox 3.0.10 Linux/3.5.7 XP, Opera 10.10 Linux or IE8 XP. I can't see why but it may be to do with the recursion (showtable calls onclick calls addit which calls showtable ...). Somehow it is not seeing the addit routine the second time round. It is meant just to add a line. Eventually it needs to be a complex table but this is for illustration. There are other ways to solve this but this would be the simplest - if it worked! What happens is that one line is added OK but then it chokes. This is what makes me think it is the recursion but I can't see otherwise how to make it write the updated text. I realise I should have a document.close() in it as well and I have tried adding <![CDATA[ ... ]]> as well. Other than in Konqueror, it gives an error message saying object not found (in IE8) or more explicitly: Code: function onclick(event){ addit(4); } with 'addit is not defined' in Firebug. In Konqueror it works sweetly. Code: <!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' xml:lang='en' lang='en'> <head> <script language='Javascript' type='text/javascript'> if(typeof(sections) == 'undefined'){ var sections=['Text 0','Text 1','Text 2']; } function addit(ilocal){ sections.splice(sections.length,0,'Text '+ilocal); showtable(); } function showtable(){ var i,j,ip1; for(i=0;i<sections.length;i++){ ip1=i+1; document.write('Section ',i,': ',sections[i],'<br>'); } document.write("<input type='button' value='Add' onClick='addit(",ip1,")' /><br>"); for(j=0;j<sections.length;j++){document.write(sections[j]," ");} } </script> </head><body> <script language='Javascript' type='text/javascript'> showtable(); </script> </body> </html> Clues would be very much appreciated - my baldness coefficient is increasing daily! Hi all, I'm just starting out with Javascript as a development language and this will probably be a relatively simple problem for someone to solve for me. I am trying to access a variable (this.bodyEl.innerHTML) from within a function but get an error message indicating that it is "undefined". I know that it is a valid variable because I call it elsewhere outside of the inner function itself. I'm sure this is just a scope issue, but I'd welcome any suggestions on how to solve it with an explanation of where I've gone wrong if you have the time. Here's the code: Code: displayFeed: function(responseData) { this.bodyEl.innerHTML = "xxxx"; // I can see this var responseDoc = Presto.Util.parseXml(responseData); var items = Ext.DomQuery.select("/rss/channel/item", responseDoc); items.each(function(item, bodyHTML) { var rssTitle = Ext.DomQuery.selectValue("/title", item); var rssDescription = Ext.DomQuery.selectValue("/description", item); var rssLink = Ext.DomQuery.selectValue("/link", item); // but this results in an undefined error this.bodyEl.innerHTML = '<a href="' + rssLink + '">' + rssTitle + '</a><br/>'; }); // end of items processing } This is a fragment of the code from my script. The first access of "this.bodyEl.innerHTML" works fine, but the second access in the items.each loop doesn't and I get an undefined variable error. Is this a scoping problem, and if so how is it best solved. Thanks in advance, Innes (NZ) Whenever i try to use this function it gives me either - NaN, or undefined what am i doing wrong? The objective of these functions are to change x and y coordinates into SAN (Simplified Algebraic Notation) for use in the Chess Game's DataFile (PGN file format). Live Running DHTML App: http://daomingjin.googlepages.com/ChessManager.html 140kb Zip-Archive: http://daomingjin.googlepages.com/ScoreMatev1.zip here are the functions in Question: Code: function XCoordToSAN(x) { // Convert the x coordinate of the piece to partial SAN (Simplified Algebraic Notation) for(var xCoord = 0; xCoord > xCoord * 7; xCoord++) { if(x == xCoord * BlockSize) { var SANx = xCoord; } } return SANx; } function YCoordToSAN(y) { var Letters = ["A", "B", "C", "D", "E", "F", "G", "H"]; // Convert the y coordinate of the piece to partial SAN (Simplified Algebraic Notation) for(var yCoord = 0; yCoord > yCoord * 7; yCoord++) { if(y == yCoord * BlockSize) { var SANy = Letters[yCoord]; } } return SANy; } this is how i'm calling the functions: Code: var oldPGNx = XCoordToSAN(oldXposition); var oldPGNy = YCoordToSAN(oldYposition); var newPGNx = XCoordToSAN(newXposition); var newPGNy = YCoordToSAN(newYposition); NewPGNData = oldPGNx + oldPGNy + "-" + newPGNx + newPGNy + " "; // Finally update the Data document.getElementById("PGNArea").value = OldPGNData + NewPGNData; I have a function where in I call another function that assigns a value to a var. e.g. Code: function setVar{ var thisVar = 'hello'; return thisVar; } function callFuncSetVar { var newVar = setVar(); alert(newVar); } For some reason my code below is returning 'undefined'. But when I place an alert(); before the 'return' it shows the correct value. However when I place an alert(); to show the var that is set to what the function returns it says 'undefined'. Firebug throws no errors. I am using a little bit of jQuery. I have a slideshow that allows the user to see the previous slide title and the next slide title along with the current slide and its content. I tested locally not in WP and the code worked fine. Once I placed my source within WP everything went south. I inspector the first line in the script seems to be what is having the issues - $(window).load(function(){ and I am unsure what to do next. The source was used from Edit fiddle - JSFiddle the page I am trying to get to work is located here - Sevices | Q&D CONSTRUCTION, INC.Q&D CONSTRUCTION, INC. I am open to any suggestions. Code: <script type='text/javascript' src="//cdnjs.cloudflare.com/ajax/libs/jquery.cycle2/20130801/jquery.cycle2.min.js"></script> <style type='text/css'> .cycle-slide { width: 100%; text-align: center; } img { max-width: 300px; } #next { float: right; } #prev { float: left; } .center { text-align: center; } </style> <script type="text/javascript">//<![CDATA[ $(window).load(function(){ var slideshow = $('.cycle-slideshow'); maxSlides = slideshow.data('cycle.opts').slideCount; slideshow.on({ 'cycle-update-view': function(event, optionHash, outgoingSlideEl, incomingSlideEl, forwardFlag) { UpdateTitles(); } }); function UpdateTitles(){ var currentSlide = slideshow.data('cycle.opts').currSlide; activeSlide = $(".cycle-slide-active"); activeTitle = activeSlide.data('title'); if(currentSlide == 0){ nextTitle = activeSlide.next().data('title'); prevTitle = $(".cycle-slide").eq(maxSlides).data('title'); } else if(currentSlide == maxSlides-1){ prevTitle = activeSlide.prev().data('title'); nextTitle = $(".cycle-slide").eq(0).data('title'); } else { nextTitle = activeSlide.next().data('title'); prevTitle = activeSlide.prev().data('title'); } $('h1').html(activeTitle); $('#prev').html("Previous: "+prevTitle); $('#next').html("Next: "+nextTitle); } UpdateTitles(); });//]]> </script> I know I shouldn't be having this problem at this stage. But what have I done wrong? I have my main page, I have my onload page and in that onload page I call a function: And then I get the error message: Fatal error: Call to undefined function OpenChat() The main page code (I've cut out the irrelevant scripts); Code: <?php session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] !='')){ header ("Location: Welcome.php"); } $Sfullname=$_SESSION['fullname']; $SMyPId=$_SESSION['MyPId']; ?> <!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"> <html> <title></title> <head> <script type="text/javascript"> function OpenChat(Msg){ loadgetdiv(); document.getElementById('<?php echo $Newdiv; ?>').style.display="block"; loadChatComplex('<?php echo $NewThisFile; ?>','<?php echo $Newdiv; ?>',Msg); } </script> <script type="text/javascript"> function loadChatCheck(File,ID,Tile,TID){ loadQuickCheck(File,ID); dodo = setInterval(function(){loadQuickCheck(Tile,TID)},5000); } </script> <script type="text/javascript"> function loadQuickCheck(File,ID){ if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById(ID).innerHTML=xmlhttp.responseText; malaky = setInterval(function(){loadQuickCheck(File,ID)},20000); } } xmlhttp.open("POST",File,true); xmlhttp.send(); } </script> </head> <body onload="loadChatCheck('getCheckNewMessages.php','txtHintCheckNewMessage','getFriendsOnline.php','txtHintShowFriends')"> <div class="mainpage"> <?php include("headermenu.php"); ?> <div id="txtHintShowFriends"></div> <div id="txtHintCheckNewMessage"></div> <br /><br /> </body> </html> AND the onload/getCheckNewMessages.php is PHP Code: <?php session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] !='')){ header ("Location: Welcome.php"); } $SMyPId=$_SESSION['MyPId']; include("dbconnect.php"); $result = mysql_query("SELECT COUNT(*) as newchat FROM chat WHERE chattee='{$SMyPId}' AND stat='new'"); $row = mysql_fetch_assoc($result); $total=$row['newchat']; echo 'This is ' . $total .'<br />'; if ($total >=1){ $result = mysql_query("SELECT * FROM chat WHERE chattee='{$SMyPId}' AND stat='new'"); while($row = mysql_fetch_array($result)){ $doormouse=$doormouse . ';' . $row['ChatID']; } $listees=explode(';',$doormouse); foreach($listees as $listor){ echo 'This is ' . $listor . '<br />'; $result = mysql_query("SELECT * FROM chat INNER JOIN allusers ON chat.chatter=allusers.PId WHERE chat.ChatID='{$listor}' "); while($row = mysql_fetch_array($result)){ echo "{$SMyPId};{$row['chatter']};{$row['fullname']};{$row['ref']}"; } echo $battlebox . '<br />'; $steptoe=OpenChat($battlebox); } $sql="UPDATE chat set stat='' WHERE ChatID='{$chatID}' "; mysql_query($sql,$con) or die(mysql_error()); } ?> Needless to say I am trying to create an instant chat. |