JavaScript - Cannot Set Property 'value' Of Undefined (anonymous Function)
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. Similar TutorialsHi All, I'm trying to convert an anonymous function to a real function (nesting is getting out of hand), however the msg object becomes undefined after conversion. Here is the converted anonymous function which fails: https://gist.github.com/2587613 and here is the original anonymous function which works: https://gist.github.com/2587667 Any help would be greatly appriciated What I want to do is have a two-dimension array where some of the elements point to the value in another element. I have done this successfully in PHP using referfences (=&) and now I want to do it in JavaScript. My JS skills are limited but I found this post explaining how it can be done - http://stackoverflow.com/a/1687183 Here's the code from that - Code: Function.prototype.toString = function() { return this(); } var x = 1; var y = function() { return x } x++; alert(y); // prints 2 It looks like it will do what I need to do. However, I want to use a two-dimension array, and if I try this it doesn't work - Code: for (var a = 2; a <= 5; a++) for (var b = 1; b < a; b++) matrix[a][b] = function() { return (matrix[b][a]) }; matrix is the two-dimension array which is alreay set up with some values. The two for loops are structured to fill in the rest of the values as references to existing values (it's a 5 x 5 array). The problem is coming from function() { return (matrix[b][a]) } because instead of the values for a and b being used in the creation of the anonymous function the actual variable names are used instead. Then later when I attempt to read one of the values setup by this it is "undefined" because the anonymous function is tries to return matrix[a][b] rather than matrix[4][2]. Can anyone help? Thanks! I've been going through this great tutorial on how to implement a type-ahead feature on a text field and there's something which hopefully you guys can explain. On the third page there is this function. Code: AutoSuggestControl.prototype.init = function () { var oThis = this; this.textbox.onkeyup = function (oEvent) { if (!oEvent) { oEvent = window.event; } oThis.handleKeyUp(oEvent); }; }; What I don't understand is this line: this.textbox.onkeyup = function (oEvent) { I know about anonymous functions, but I don't know where the value for the parameter oEvent is going to come from. Can someone explain this? Thanks! :) Hello! I'm working with nested functions and trying to pass a 'this' value to an anonymous being used in an assignment for an event listener. Here's the basics of my code: Code: <div id='abc'></div> <script type='text/javascript'> var abc = function () { this.myFunction = function() { var myObj myObj = document.createElement("input"); myObj.setAttribute("type", "button"); myObj.setAttribute("value", "Click Me"); myObj.addEventListener("click", function () { this.doDing(); }, false); document.getElementById('abc').appendChild(myObj); } this.doDing = function () { alert('ding'); } } var myInstance = new abc(); myInstance.myFunction(); </script> So, this should plop a button inside our DIV and when clicked I'd like it to run the alert-ding; unfortunately it seems to want to run the function as defined under the buttons object which doesn't work out too well. Any suggestions? Thanks! Hey all, I am confused about the true difference between the two below examples. Code: first example: // Demonstrating a problem with closures and loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array(); // Loop through myArray and create a closure for each that outputs that item for (var i = 0; i < myArray.length; i++) { var theItem = myArray[i]; closureArray[i] = function() { document.write(theItem + “ < br / > ”); } } // Loop through the closures and execute each one. for (var i = 0; i < closureArray.length; i++) { closureArray[i](); } Here we iterate through the length of myArray, assigning the current index of myArray to theItem variable. We declare closureArray 4 times as an anonymous function. The anonymous function in turn declares the predefined write() function, which is passed parameters. Since write() is in closureArray() a closure is created??? During each iteration, theItem is reassigned its value. The four closures reference this value. Since they reference this same value and since this value is reassigned ultimately to the value of the fourth index position, tHe time we execute closureArray later on, all four closures output the same string. This is because all four closures are within the same scope "the same environment" and therefore are referencing the same local variable, which has changed. I have a couple of problems with this example: 1) I thought a closure is a function that is returned - the inner function is not returned above. 2) theItem is not even a local variable of the parent function (closureArray) - I thought in order for a closure to work, the inner function only accesses the local variables of the outer function, but in this case the local variable is defined OUTSIDE of the parent function. 3) The guy says the "the four closures are sharing the same environment." The thing is even in the second example, they are sharing the same environment. Second example: Code: // A correct use of closures within loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array(); function writeItem(word) { return function() { document.write(word + “ < br / > ”); } } // Loop through myArray and create a closure for each that outputs that item for (var i = 0; i < myArray.length; i++) { var theItem = myArray[i]; closureArray[i] = writeItem(theItem); } // Loop through the closures and execute each one. for (var i = 0; i < closureArray.length; i++) { closureArray[i](); } Here we iterate over the length of myArray (4 times), assigning the index of myArray to theItem variable. We also return a function reference to the closureArray during each iteration (closureArray[i]), where i is index number so we assign 4 functon references. So when we iterate through myArray, we immediatelly call the writeItem() fucntion passing an argument of theItem at its current value. This returns a child anonymous function and when that child function is called, it will execute a block that calls the predefined write() method. We assign that returned anonymous function to the variable closureArray. Hence, closureArray holds a reference to that anonymous function. So closureArray during each iteration holds a reference to the anonymous function and we later call closureArray, which in turn calls the anonymous function, therefore calling the predefined write() function to output the local variable of the parent function. This outputs each distinct index of myArray. QUESTION: This is because since we created the closure, when we call writeItem, passing theItem argument, since theItem is a local variable of the parent function of the closure, it is never destroyed when we later call closureArray (the reference to the child anonymous function)? Yet weren't we using a closure in the first example as well? So whey wasn't those variables preserved? I don't think it has anything to do with assigning a returned anonymous function to closureArray. Even though an anonymous function creates a new memory position in the javascript engine, therefore not overwriting the other function references we create during the iteration, it's still referring to a local variable declared outside the reference. So if it's about the closure retaining value of parent's local variable even after exiting the parent function allowing for the current indexes to be preserved, then why did the closure in the first example fail to retain each index? Thanks for response Hi, This is my first post while learning Javascript and jQuery as total noob. I have something like this: Code: var desc = "This is your title and here is even more that might be added so that we can get at least 60 characters or so"; var desc = desc.trim().substring(0, 40).split(" ").slice(0, -1).join(" ") + "...more"; alert(shortText ); It is actually being used on a page that calls a description from a MySQL table, but this example fails in exactly the same manner. Although FF and other browsers successfully initiate the script with errors, but IE loops endlessly and freezes up. FireBug reports "reference to undefined property a[d]". Using jQuery 1.6.2. I'm not really sure what property is undefined here and how this can work without freezing IE. Thanks in advance for any help! AJ The line "xmlHttp.onreadystatechange = function()" Does the following error, i dont know whats wrong. The code: Code: function MakeRequest() { var xmlHttp = getXMLHttp(); var page = document.getElementById("page").value; var content = document.getElementById("code").value; xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4 && xmlHttp.status==200) { HandleResponse(xmlHttp.responseText); } } xmlHttp.open("POST", "edit.save.php", true); xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttp.send("page="+page+"&content="+content+""); } function getXMLHttp() { var xmlHttp try { //Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch(e) { //Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { alert("Your browser does not support AJAX!") return false; } } } } function HandleResponse(response) { document.getElementById('SavedFile').innerHTML = response; } What i'm trying to accomplish is two things. To select the page i want to load in each tab then select how many of thoughs tabs i wish to open. When the number of tabs is selected i want it to launch. i also have a refresh button that works i just can't get the windows to load. by the way for this project i want it to open the same url that is selected on all of the tabs. Here is what i have: <html> <head> </head> <form name="myform"> <select name="mySelectbox"> <option value="">Choose a destination...</option> <option value="http://www.yahoo.com/">YAHOO</option> <option value="http://www.google.com/">GOOGLE</option> <option value="http://www.altavista.com/">ALTAVISTA</option> <option value="http://www.amazon.com/">AMAZON</option> </select> </form> <form name = "myform2"> <select name = "numberWindows" onchange = "openThem()"> <option value = "0">Choose....</option> <option value = "1">TEST</option> <option value = "2">2</option> <option value = "3">3</option> <option value = "4">4</option> <option value = "5">5</option> </select> </form> <script> function open_win() { var myurl = parseInt(document.myform.myselectbox.value); window.open("myurl"); } </script> <script type = "text/javascript"> var i; function openThem() { var val = parseInt(document.myform2.numberWindows.value); for (i =0; i < val; i++) { open_win(); } } document.write('<form><input type=button value="Refresh To Do Again" onClick="history.go()"></form>') </script> </body> </html> Can someone please help. I'm just trying to learn how this is done. Thanks. Good day! Here is the problem, setting the slider to the site, here's an example: http://wowslider.com/best-jquery-sli...near-demo.html and do not connect different effects on this slider, such as buttons on the sides and smooth shifting slides. When you see the code generates this error: Uncaught TypeError: Cannot read property addEventListener' of undefined I do not know what this error, help, error on this site: http://uh219381.ukrdomen.com/ Or here's the code: http://uh219381.ukrdomen.com/themes/...1/wowslider.js sorry for my English I do not really understand what is happening to my code but it just tell me the following: Code: document.getElementById("#movingword") is null How could the movingword be null when I have declared it in my code? The following is my code: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="language" content="english"> <meta http-equiv="Content-Style-Type" content="text/css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <title></title> <style type="text/css"> body { background-color:#000; } #scenery { position:relative; } #moving { position:absolute; float:right; top:100px; left:50px; } #movingword { position:absolute; float:right; top:0px; left:0px; } </style> <script type="text/javascript"> var a=120; $(document).ready(function() { document.getElementById("#movingword").style.top = a + "px"; }); </script> </head> <body> <font color=white><h1> Hello World </h1></font> <div id="scenery"> <img src="http://www.deshow.net/d/file/travel/2009-10/new-zealand-scenery-738-20.jpg" alt=""> <div id="moving"> <img src="http://maadinfo.com/images/blinking.gif" alt=""> </div> <div id="movingword"> <font color="yellow"><font size="3"><b>This is the place</b></font><br>Welcome!</font> </div> </div> </body> </html> 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> I wrote a script that creates 2 absolutely positioned divs, in perfect alignment, one on top of the other. I want to use javascript to manipulate the display property of each div to show one div at a time by toggling each div's display property between none and block with an onClick event handler attached to the link. This script works fine when the javascript function has no parameters, because the div id's are inserted directly into the getElementById function. When I say it works, I mean the div with id=cal2 displays onload, then disappears when the Show Calendar link is clicked. The div that appears in its place has a link that does the reverse when clicked. I want to create multiple pairs of overlapping divs that toggle their visibility, so I want to put parameters inside the functions that identify the specific pair of divs that need to be toggled per function call. When I try to use variables/parameters in the functions to insert specific div id's into getElementById, it does not work. PLEASE NOTE, the code below has div id's in green that don't have quotes of any kind. It still works in my firefox browser. I thought id's needed quotes, but it works without. I don't know why. The code below works, but has no parameters in the functions: Code: <!DOCTYPE html> <xhtml> <head> <title>Practice Calendar</title> <style type="text/css"> .practicecalendar { position: absolute; top: 0px; left: 0px; margin: 0; width: 18em; background: #B3FF99; text-align: center; } .practiceschedule { position: absolute; top: 0px; left: 0px; margin: 0; width: 18em; background: #99E6FF; text-align: center; } </style> <script type="text/javascript"> <!-- function showSchedule(){ document.getElementById('sch2').style.display = 'block'; document.getElementById('cal2').style.display = 'none'; } function showCalendar(){ document.getElementById('cal2').style.display = 'block'; document.getElementById('sch2').style.display = 'none'; } //--> </script> </head> <body> <div id= cal2 class='practicecalendar' style=' display: block; '> <p>Calendar</p> <p><a href='' onClick='showSchedule(); return false'>Show Schedule</a></p> </div> <div id= sch2 class='practiceschedule' style=' display: none; '> <p>Schedule</p> <p><a href='' onClick='showCalendar(); return false'>Show Calendar</a></p> </div> </body> </xhtml> When I add the information in red to the same script above, I get the script below that does not work. Code: <!DOCTYPE html> <xhtml> <head> <title>Practice Calendar</title> <style type="text/css"> .practicecalendar { position: absolute; top: 0px; left: 0px; margin: 0; width: 18em; background: #B3FF99; text-align: center; } .practiceschedule { position: absolute; top: 0px; left: 0px; margin: 0; width: 18em; background: #99E6FF; text-align: center; } </style> <script type="text/javascript"> <!-- function showSchedule( sch,cal ){ document.getElementById( 'sch' ).style.display = 'block'; document.getElementById( 'cal' ).style.display = 'none'; } function showCalendar( cal,sch ){ document.getElementById( 'cal' ).style.display = 'block'; document.getElementById( 'sch' ).style.display = 'none'; } //--> </script> </head> <body> <div id= cal2 class='practicecalendar' style=' display: block; '> <p>Calendar</p> <p><a href='' onClick='showSchedule( 'sch2','cal2' ); return false'>Show Schedule</a></p> </div> <div id= sch2 class='practiceschedule' style=' display: none; '> <p>Schedule</p> <p><a href='' onClick='showCalendar( 'cal2','sch2' ); return false'>Show Calendar</a></p> </div> </body> </xhtml> When I remove the single quotes from the blue code , it does not work either. Code: <!DOCTYPE html> <xhtml> <head> <title>Practice Calendar</title> <style type="text/css"> .practicecalendar { position: absolute; top: 0px; left: 0px; margin: 0; width: 18em; background: #B3FF99; text-align: center; } .practiceschedule { position: absolute; top: 0px; left: 0px; margin: 0; width: 18em; background: #99E6FF; text-align: center; } </style> <script type="text/javascript"> <!-- function showSchedule(sch,cal){ document.getElementById('sch').style.display = 'block'; document.getElementById('cal').style.display = 'none'; } function showCalendar(cal,sch){ document.getElementById('cal').style.display = 'block'; document.getElementById('sch').style.display = 'none'; } //--> </script> </head> <body> <div id=cal2 class='practicecalendar' style=' display: block; '> <p>Calendar</p> <p><a href='' onClick='showSchedule( sch2,cal2 ); return false'>Show Schedule</a></p> </div> <div id=sch2 class='practiceschedule' style=' display: none; '> <p>Schedule</p> <p><a href='' onClick='showCalendar( cal2,sch2 ); return false'>Show Calendar</a></p> </div> </body> </xhtml> Thanks for reading all of this. Does anyone know what I'm missing? 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 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> 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 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 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 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! 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; |