JavaScript - Ajax Callback: Passing Arguments, And Return Vals
I have a project that uses and Ajax call but it appears that the call back
function cannot take arguments, nor return values. However, I have wrapped another function inside the call back function that takes xmlhttp.responseText as the argument and returns values that are supposed to be placed in a global array. If I do, for instance: callback function code.... globalArray = someFunction(xmlhttp.responseText) alert(globalArray), I get the expected values. but a function is called later to query the contents of the global array the global array is empty (No other code or functions exist in this project to alter the global array) Primary dev client is FireFox 3x on Mac OSX Is this a bug, or is there some other aspect of javascript that I need to know about? I am using ajax here because javascript does not have an array shuffling function and php does. So I send an array to the server, have it shuffled by the server and returned to the requesting page. Similar TutorialsI'm updating a database w/o "reloading" the page using jquery & ajax. Everything works fine, but I need to display an error (in php - mysql_error()) in the error callback function. I also don't think that the success/error callbacks are working as even when I changed the password in to the mysql server in the php file, I got the success message :S Can any1 help me out? this is the php script Code: <?php /*$fp = fopen('data.txt', 'a+'); fwrite($fp, 'ok'); fclose($fp);*/ $sections = $_REQUEST['sections']; $fontColor = $_REQUEST['fontColor']; $bgcolor = $_REQUEST['bgcolor']; $font = $_REQUEST['font']; $fontSize = $_REQUEST['fontSize']; $lineHeight = $_REQUEST['lineHeight']; $letterSpacing = $_REQUEST['letterSpacing']; $fontStyle = $_REQUEST['fontStyle']; //$tekst = $_REQUEST['tekst'] $connect = mysql_connect("localhost", "root", "password") or die ("Unable to connect to the database"); mysql_select_db("ipsum") or die ("doesnt exist: " . mysql_error()); $update = "INSERT INTO con (Sections, Fontcolor, BackgroundColor, Font, FontSize, LineHeight, LetterSpacing, FontStyle) VALUES ('".$sections."', '".$fontColor."', '".$bgcolor."', '".$font."', '".$fontSize."', '".$lineHeight."', '".$letterSpacing."', '".$fontStyle."')"; // the content of 'data.txt' is now 123 and not 23! mysql_query($update) or die ("unable to update: " . mysql_error()); mysql_close($connect); ?> and this is what I currently have for the error Code: error: (function (){$('#errorMessage').fadeIn("slow").delay(1000).fadeOut(2000);}), but that needs to change... The only way I can figure out to invoke an event handler, like onchange or jquery's change, after an ajax response is rendered to page is by triggering event handler within the ajax call. Is there a better way to do this? It looks like bad code but this is only where I am at right now in rendering a table to page and now allowing user filtering: (function($){ var listview = $('#listview'); $('#dashboard a').click(function(){listLoader(this);}) var listLoader = function(context, options){ for(var i = 0; i < arguments.length; i++){ var data = arguments[1] } var url = context.href.substring(context.href.lastIndexOf('#') + 1); $.ajax({ type: 'GET', url: '/' + url, data: data, dataType: 'html', error: function(){}, beforeSend: function(){}, complete: function() {}, success: function(response) { listview.html(response); $("select").change(function(){ var option = $(this).val(); listLoader(context, option); }) //end for change } }) } })(jQuery) Could somebody help me please to explain what I'm doing wrong.... a have this html file with references to some javascripts (datagrid from http://www.datatables.net) and this html file work ok..I mean javascripts a css styling works with table... but when I call this page by ajax and callback (this html page) is forward back into another div , table doesn't work ....just data from page but now functionality from javascript and css styling... how should I force callback result to use javascript and css? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html><head> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> <link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/media/images/favicon.ico"> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="http://www.datatables.net/rss.xml"> <style type="text/css" media="screen"> @import "media/css/demo_page.css"; @import "media/css/demo_table.css"; @import "http://www.datatables.net/media/css/site_jui.ccss"; @import "media/css/demo_table_jui.css"; @import "media/css/themes/base/jquery-ui.css"; @import "media/css/themes/smoothness/jquery-ui-1.7.2.custom.css"; /* * Override styles needed due to the mix of three different CSS sources! For proper examples * please see the themes example in the 'Examples' section of this site */ .dataTables_info { padding-top: 0; } .dataTables_paginate { padding-top: 0; } .css_right { float: right; } #example_wrapper .fg-toolbar { font-size: 0.8em } #theme_links span { float: left; padding: 2px 10px; } </style> <script type="text/javascript" src="media/js/complete.js"></script> <script src="media/js/jquery-1.4.4.min.js" type="text/javascript"></script> <script src="media/js/jquery.dataTables.min.js" type="text/javascript"></script> <script type="text/javascript" src="media/js/jquery.dataTables.editable.js"></script> <script src="media/js/jquery.jeditable.js" type="text/javascript"></script> <script src="media/js/jquery-ui.js" type="text/javascript"></script> <script src="media/js/jquery.validate.js" type="text/javascript"></script> <script type="text/javascript" charset="utf-8"> $(document).ready( function () { $('#example').dataTable().makeEditable({ sUpdateURL: "update.php", sDeleteURL: "delete.php" }); } ); </script> </head> <body id="index" class="grid_2_3"> <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"> <thead> <tr> <th> ID</th> <th> user</th> <th> password</th> <th> first</th> <th> last</th> <th> company</th> </tr> </thead> <tbody> <tr class="even_gradeA" id="1"> <td> 1 </td> <td> XY </td> <td> passwoed </td> <td> Ja </td> <td> jajovic </td> <td> 2 </td> </tr> <tr class="even_gradeA" id="2"> <td> 2 </td> <td> jojo </td> <td> fa25af5301e2dda1fddea740200aa10ab6c70d86 </td> <td> jojo </td> <td> jojovicko </td> <td> 2 </td> </tr> <tr class="even_gradeA" id="3"> <td> 3 </td> <td> kuk </td> <td> d588aebb93e3adf70eac1fb479d6d53f9dc21816 </td> <td> kuk </td> <td> kukovic </td> <td> 3 </td> </tr> <tr class="even_gradeA" id="10"> <td> 10 </td> <td> admin </td> <td> f865b53623b121fd34ee5426c792e5c33af8c227 </td> <td> admin </td> <td> adminovic </td> <td> 3 </td> </tr> </tbody> </table><button id="btnDeleteRow">Delete</button> </body> </html> Should be simple, but I'm having a complete brain fart. I need to call a function, with a parameter that triggers something relative to that parameter. Pseudo Example Code: function respawn(n) { case 1 //respawn monster1 code case 2 //respawn monster 2 code case 3 //respawn monster 3 code } if(killed monster1) {respawn(1)} //respawn(monster1) is what I want to do if(killed monster2) {respawn(2)}//respawn(monster2) is what I want to do if(killed monster3) {respawn(3)}//respawn(monster3) is what I want to do I can... Code: function respawn1(){ //respawn monster1 code } function respawn2() { //respawn monster2 code } function respawn3() { //respawn monster3 code } if(killed monster1) {respawn1()} if(killed monster2) {respawn2()} if(killed monster3) {respawn2()} but if I have 10+ monsters I just figured a case structure would be good, or passing the monster to respawn to a single respawn() function......but all the switch examples I could find were based on dateTime which gave case 1-7 based on what day it was, and didn't show how you set your own cases like monster1, monster2, monster3.... I know this is a basic concept...I've read about functions he http://www.quirksmode.org/js/function.html and at w3schools of course but can't figure out how to apply it to my situation Thanks i've got a project to be done using javascript and html....i don't know how to pass the arguments from <input type="text"> to the javascript function i'm using in my program. i just want the javascript script to calculate the input given by the user and return the answer. here is the program: Code: <html> <head> <title> Taxi Fare </title> <script lang="text/javascript"> // calculates taxi fare based upon miles traveled // and the hour of the day in military time (0-23). var taxiFare = function (milesTraveled, pickupTime) { var baseFare = 2.50; var costPerMile = 2.00; var nightSurcharge = 0.50; // 8pm to 6am, every night var cost = baseFare + (costPerMile * milesTraveled); // add the nightSurcharge to the cost if it is after // 8pm or before 6am if (pickupTime >= 20 || pickupTime < 6) { cost += nightSurcharge; } return cost; }; </script> </head> <body> <form> <input type="text" onclick="taxiFare()" value="Call function"> <input type="Submit" value="OK" onclick="taxiFare()"> <input type="reset" value="Clear"> </form> <script type="text/javascript"> document.write("Your taxi fare is ₹" + taxiFare(5,2)); </script> </body> </html> pls it would be of great help. Thanx. Please help, I have been looking at this all day and I know there must be a simple fix! How do I pass results back to textService so that I can make a call such as textResult = textService(text to pass in); I don't want to use a global variable if I can avoid it. This is the code Code: function textService(text){ req.open("GET", "http://....?text="+text, true); req.onload = showResults; req.send(null); } function showResults() { results = req.responseXML.getElementsByTagName("Result"); } Thank you in advance I need to get this script to work, I only included what im having the problem with. I am Using jQuery Library. Here is how this should work: .btnRoof div is clicked the parent id is retrieved as var pid a function called roof is called which simply changes a css background to "color" the function perform is called to get the "color1[0]" from the array. My Problem: perform() returns the word color1, color10, color1[0], or c. instead of images/cp-roof-blue.png as listed in the array. Code: $(document).ready(function() { var color1=new Array(); color1[0]="images/cp-roof-blue.png"; color1[1]="images/cp-panel-blue.png"; color1[2]="images/cp-trim-blue.png"; function perform(name, x) { alert(name[x]); //alert([name][x]); //alert(name+'['+x+']'); //alert(color1[0]); // correct return name[x]; } function Roof(color) { $("#colorPicker .roof").css("background", "url("+color+")"); } $('.btnRoof').click(function() { var pid = $(this).parent().parent().attr("id"); Roof(perform(pid, 0)); }); }); I tried to clarify as much as possible, please let me know if I need explain further. Thanks. I don't understand the logic of Break, Return False, Return True. It was never really covered in our college class, and I see everyone using it. I got an A in the class, if that 'proves' that I really tried to apply myself. NOTE: I understand what the function is doing. I just don't understand WHEN to use break, return false or return true if the the translator can determine the conditional statements. PHP Code: function submitForm(){ var ageSelected = false; for (var i=0; i<5; ++1){ if (document.forms[0].ageGroup[i].checked == true) { ageSelected = true; break; } } if (ageSelected == false){ window.alert("You must select your age group"); return false; } else return false; } if the the translator can determine the conditional statements, why not write it like this: PHP Code: function submitForm(){ var ageSelected = false; for (var i=0; i<5; ++1){ if (document.forms[0].ageGroup[i].checked == true) { ageSelected = true; break; // what's the point for the 'break'? Won't the rest of the code be ignored since it passed the first condition? } } if (ageSelected == false){ window.alert("You must select your age group"); return false; } // why not leave the last else out? is it just a 'safety' catch, in case something other than true or false is inputted? else return false; // what's the point? } Questions: Why use return true, if the translator knows it's ture? Why use "return false" if the translator knows it's false and the alert window has already gone up? why not use "break" to stop the code? Why use the "return false" at the end "else" statement? Hi room, Hey, I opened up the source code for this page in google chrome and since i'm learning javascript, i wanted see if i could "read" it and figure out what was going on. I'm am having the hardest time understanding "return false" and "return true". Could someone step me through this via interpreting this code (in bold typeface): Code: var DefaultValue = 'Search'; function clearSearch() { if (document.searchForm.q.value == DefaultValue) { document.searchForm.q.value = ''; } } function validateSearchHeader() { if ( document.searchForm.q.value == '' || document.searchForm.q.value.toLocaleLowerCase() == DefaultValue.toLocaleLowerCase() ) { alert('Please enter at least one keyword in the Search box.'); document.searchForm.q.focus(); return false; } return true; } Thanks! So I hacked up a version of the wowSlider to work as a timed rotating background... I need to know how to add a callback funtion so that I can make the Image and link that is in front of the wowSlider to change each time the background changes. Here is what I have so far: http://www.eclipse2.com/testing/new_layout/ Help would be greatly appreciated. Hi, I having problems using 'this' in an objects method. I have simplified the problem - see image. I instantiate object obj1 which inturn instantiates subObj1. subObj1 is a slave to obj1. obj1 registers a handler function called method1 with subObj1 so that subObj1 can tell obj1 when it has finished. For example: call subObj1.subMethod2() to get the sub object to do something. subObj1 calls subMethod1 when its finished with its task, which inturn causes method1 to be called. If I call method1 directly from obj1 'this' refers to obj1. However when method1 gets called by the subObj1 through the event handler mechanism, I find that 'this' has been changed to refer to subObj1. This is a problem as now method1 has lost all connection with its object obj1. If I define method1 within the 'Class1' function, I can get it to work if I use the 'var me = this;' trick, but if you have lots of methods within Class1() with further nesting this can get a bit hard to read. So, can someone tell me how to deal with 'this' changing. I.e. I want 'this' to refer to obj1 within method1. Code: <html> <body> <script type="text/javascript"> function Class1(){ this.prop1 = "prop"; this.subObj1 = new SubClass1(); //sub-object this.subObj1.subMethod1 = this.method1; //register handler } Class1.prototype.method1 = function(){ console.log(this.prop1); } function SubClass1(){ this.prop1 = "subObjProp"; this.subMethod1; this.subMethod2 = function(){ this.subMethod1(); }; } obj1 = new Class1(); obj1.method1(); //prints 'prop' obj1.subObj1.subMethod2(); //prints 'subObjProp' </script> </body> </html> On another note, there seems to many ways of defining methods (e.g using 'prototype' etc etc) and I gettting sick and tierd of a 'trial and error' approach to get things working. Can anyone recomend a good resourse that sets out the best way to design with javascript so I dont keep running into these issues. (E.g. is my scheme of communicating with sub-objects a bit crazy, and is there a better way.) Thanks. so, I should start by saying that I don't really understand callbacks (but I understand what they do), and here's the thing: html5 browser geolocation has an error callback which works fine EXCEPT if the user is using FF and refuses to share their location. In IE and Chrome, this produces a "permission denied" error which you can then handle. But firefox just sits there because it never receives the error. Here's an example - click on Not now in FF to see what I mean. So the only solution I can see is to make some special case for FF and this is where my question comes in - can I set a condition within the callback that says something like if it wasn't successful, but you didn't get an error, do this... I thought that if (!position&&!error) {useMaxMind("Firefox fallback"); } might do it, but it can't go in the error callback (I guess because that only fires if an error is detected) and it doesn't work in the main function (I guess because if that code runs it means the location has been found)... anyway. Here's what I have for the moment, which just sets a timeout as soon as it loads. It would be nice to have something a bit more elegant, though. thanks in advance... Code: function initialize() { // try W3C standard approach var geoTimeout = 10000; var timeOuthandler = setTimeout("useMaxMind('Timeout')", geoTimeout); if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var latLong = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); alert("geolocation successful"); clearTimeout(timeOuthandler); showMap(latLong, 16); }, function (error) { switch (error.code) { case 0: message = "Something went wrong: " + error.message; break; case 1: message = "You denied permission to this page to retrieve a location."; break; case 2: message = "The browser was unable to determine a location: " + error.message; break; case 3: message = "The browser timed out before retrieving the location."; break; } clearTimeout(timeOuthandler); useMaxMind(message); }, {timeout:geoTimeout} ); } else { useMaxMind("No browser support"); } } Hi all, I am trying to pass some dynamic values for use with javascript or more specifically AJAX... I had a set up looking something like the following; Code: <input type="button" onclick="ajaxFunction()" value="Add Favourite"/> <input type="text" name="school_id" id="school_id" value="<?php echo $school_id; ?>" /> <input type="text" name="teacher_id" id="teacher_id" value="<?php echo $teacher_id; ?>" /> Code: <script language ="javascript" type="text/javascript"> <!-- //Browser Support Code function ajaxFunction(){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); }catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); }catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data // sent from the server and will update // div section in the same page. ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxDiv'); ajaxDisplay.value = ajaxRequest.responseText; } } // Now get the value from user and pass it to // server script. var school_id = document.getElementById('school_id').value; var teacher_id = document.getElementById('teacher_id').value; var queryString = "?sid=" + school_id; queryString += "&tid=" + teacher_id; alert(queryString); ajaxRequest.open("GET", "ajax_insert_favourite.php" + queryString, true); ajaxRequest.send(null); } //--> </script> however because it is possible for there to be more than one button, i.e. many teachers can be returned the javascript would also output 1 and 1. I need someway of making this unique to the id's... I think that passing arguments/params might be the solution but I'm having a hard time implementing it; I've tried the following; Code: <input type="button" onclick="ajaxFunction('school_id','teacher_id')" value="Add Favourite"/> Code: <!-- //Browser Support Code function ajaxFunction(school_id,teacher_id){ But once I do this, it no longer even make the call. Can anyone advise here, I'm a relative newbie to javascript/AJAX etc. Many thanks, Greens85 Let's say I'm defining an object and I want the constructor to take one input and ten save it. I'd like to do something like this: function apple(color) { this.color = arguments.color; } But of course that doesn't work because arguments isn't a scope. My question is, is there a scope I can use. What I've been doing instead is this: function apple(new_color) {this.color = new_color;} But that just seems less than perfectly pretty. Hope you can help. I'm currently building a website and trying to integrate a javascript image 'tranisition' effect into mm_swapimage and failing. My knowledge of Javascipt is limited but without knowing the 'arguments' for mm_swapimage, it's impossible (looks similar to vb, but can't find an answer anywhere) I want the effect to work on a 'timed' event rather than 'OnMouseOver' so have added script to change that (which is probably the issue!) I can get both to work idependantly but not together. I've simplified the page and pasted the code below, as it stands the 'effect' works, but it only uses the primary image, not the other image in the array. I'm using DW CS4 and the transition extension is called FlevOOware. Thanks Michael 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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript"> <!-- function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } function flvFSTI4(){//v1.01 this.style.filter="";} function flvFSTI3(v1,v2){//v1.01 var v3;if (v1.filters[0]&&v1.filters[0].status==2){v1.filters[0].Stop();}if (v2==0){v3="blendTrans(Duration="+v1.STI8+")";}else {v3="revealTrans(Duration="+v1.STI8+",Transition="+(v2-1)+")";}v1.style.filter=v3;} // Wipe Right Out function flvFSTI2(){//v1.01 var v1,v2=document,v3=v2.STI4,v4;for (v4=0;v3&&v4<v3.length&&(v1=v3[v4])&&v1.STI5;v4++){if (v1.filters&&!v2.STI7){flvFSTI3(v1,v1.STI3);v1.filters[0].Apply();}v1.src=v1.STI5;if (v1.filters&&!v2.STI7){v1.filters[0].Play();}}} // Wipe Right In function flvFSTI1(){//v1.01 // Copyright 2003, Marja Ribbers-de Vroed, FlevOOware (www.STI1.nl/dreamweaver/) var v1=arguments,v2=document,v3;v2.STI4=new Array();v2.STI7=(navigator.userAgent.toLowerCase().indexOf("mac")!=-1);for (var v4=0;v4<v1.length-2;v4+=5){v3=MM_findObj(v1[v4]);if (v3){v3.STI5=v3.src;v3.STI6=v1[v4+1];v3.STI2=v1[v4+2];v3.STI3=v1[v4+3];v3.STI8=v1[v4+4];v2.STI4[v2.STI4.length]=v3;if (v3.filters&&!v2.STI7){flvFSTI3(v3,v3.STI2);v3.onfilterchange=flvFSTI4;v3.filters[0].Apply();}v3.src=v3.STI6;if (v3.filters&&!v2.STI7){v3.filters[0].Play();}}}} function MM_swapImgRestore() { //v3.0 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; } function MM_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } // Comma separated list of images to rotate var imgs = new Array('images/DSCN1209.jpg','images/DSCN1210.jpg'); // delay in milliseconds between image swaps 1000 = 1 second var delay = 5000; var counter = 0; function preloadImgs(){ for(var i=0;i<imgs.length;i++){ MM_preloadImages(imgs[i]); } } function randomImages(){ if(counter == (imgs.length)){ counter = 0; } MM_swapImage (flvFSTI1('slider', '',7,7,1,1, imgs[counter++])); setTimeout('randomImages()', delay); MM_swapImgRestore (flvFSTI2('slider', '')); } //--> </script> </head> <body onload="preloadImgs();randomImages();"> <img src="images/DSCN1209.jpg" name="slider" width="500" height="322" id="Image1"/> </body> </html> I am a newbie and am writing a function. I want the function to refer to an arrays elements to get the biggest, but I dont know how to do this. Here is the code: Code: function unique(first,second,third) { var answer; if (first > second) { answer = first - second; } if (second > third) { answer = second - third; } if (third > first) { answer = third - first; } return answer; } //function call unique (digitArray(0,1,2)); what I am trying to do, is get the array elements to be called and give me an answer. Will I need to add the array to the function? It is further down the code after the function at the moment. Or will I need to add the array elements to the function? Hope it is clear I want to use the new keyword to instantiate an object. The catch is I want to pass in variable length arguments. Given: Code: function Foo () { this.args = Array.prototype.join.call (arguments); } var args = ["arg0", "arg1", "arg2"]; The following don't work (though I understand why): Code: new Foo.apply (null, args); new (Foo.apply (null, args)); (new Foo).apply (null, args); Any ideas on how to do what I want without modifying Foo's source code? Hello, i'm working on a 3 page survey. When hitting next, previous, or submit it passes the values of all the questions to the next page. I've got the whole thing working correcting except for one thing: When the box is "not" checked it passes no value. I'm needing it to have a value of "1" when checked and a value of "0" when not checked, and currently when its not checked and i pass the info it leaves it blank. I'd post the whole code to one of the pages but it's long , so i'll post the snipits of the code. Code: <script type="text/javascript"> /* <![CDATA[ */ function processQueryString() { var formData = location.search; formData = formData.substring(1, formData.length); while (formData.indexOf("+") != -1) { formData = formData.replace("+", " "); } formData = unescape(formData); var formArray = formData.split("&"); for (var i=0; i < formArray.length; ++i) { //document.writeln(formArray[i] + "<br />"); var sDataName = formArray[i].split("=") switch (sDataName[0]) { case ".lib_use": for (var j=0; j < document.getElementsByName(".lib_use").length; ++j) { if (document.getElementsByName(".lib_use").item(j).value == sDataName[1]) { document.getElementsByName(".lib_use").item(j).checked = true; //alert("lib_use set"); } } break; case ".lib_comp": if (sDataName[1] == 1) { document.getElementsByName(".lib_comp").checked = true; document.getElementsByName(".lib_comp").value= 1; } else { document.getElementsByName(".lib_comp").checked = false; document.getElementsByName(".lib_comp").value= 0; } break; default: alert("not caught = " + sDataName[0]); continue; } } } /* ]]> */ </script> <input type="checkbox" name=".lib_comp" id="lib_comp" value="1" /> The first case that i showed in my code is a radio button, and it passes correctly, i just wanted to show the "format" i was using in a working sense. The 2nd case is an example of the check boxes. Thanks for looking at this, and giving any suggestions you might have! Hi all, I have a newbie question. I have just started working with javascript and would appreciate some guidance. I have a webpage and there are products for sale on it(this is not live it is merely being used as practice project). Beside each product is a description a price and an 'add to cart' button. My cart is simply a div with an id of 'cart' and it has a text box within it. I need the product name to be displayed within the div (this, I have working), I also need to display the product price in the text box once the button(add to cart ) for that particular product has been pressed. Also when the button for another product is pressed, I want the cost/value for that product to be added to the other value and displayed in the text box in the cart div... I apologise for rambling on but this is the best way of me explaining my needs.... Here's where i am right now.. The HTML snippet Code: <div id ="cart"> <p><img src="images/shopping-cart.png" alt ="cart"/>Your Cart</p> <div id="sum"><!--(this is the div where the total goes)--> <input type="text" id="total" value="0" /><p>€ Your Total <input type="reset" value = "reset" /></p> </div> </div> <h2 id ="black">Blackcurrent<br /></h2> <p>€ 12.00 <input type = "submit" value ="add to cart" onClick = "shoppingCart('Blackcurrent',12)" /></p> And the javascript: Code: alert ("working"); function shoppingCart (itemName,itemValue) { /* var thePrice = Number(itemValue); return thePrice;*/ document.getElementById ("cart").innerHTML += itemName + "<br/>"; document.getElementById('total').value = Number(document.getElementById('total').value) + itemValue; } I hope i have posted correctly and am aware that i have only posted a segment of the HTML.. Please let me know if you need any more code or info.. Thanks a lot in advance for any help... Code: <html> <head> <title>Variable - Examples 1</title> <script type="text/javascript"> function Student(firstName, lastName, email, courseID, titleArray, pointsArray){ this.firstName = firstName; this.lastName = lastName; this.email = email; this.courseID = courseID; this.title = titleArray; this.points = pointsArray; this.assign = this.points.slice(0,4); this.exams = this.points.slice(-2); this.assignments = function() { return task(this.title,this.points); } this.totalPoints = function() {return addExam(this.assign,this.exams); } this.finalGrade = calcGrade; } Student.prototype = { constructor : Student, toString : studentInfo }; //assign and exam doesn't seem to hold no values inside.. ??? function addExam(assign,exams){ var exams=this.exams; var high1=exams[0]; var high2=0; while(high2<exams.length){ high1=Math.max(high1,exams[high2]); high2++; } var sum = 0; for (var i=0; i < assign.length; i++){ sum += assign[i]; } return sum + high1; } var totalPoints = addExam(); function calcGrade(){ var grade; if (totalPoints >= 190){ return "A+"; }else if (totalPoints >= 180){ return "A"; }else if (totalPoints >= 175){ return "B+" }else if (totalPoints >= 170){ return "B"; }else if (totalPoints >= 165){ return "B-"; }else if (totalPoints >= 160){ return "C"; }else if (totalPoints >= 150){ return "D"; }else if (totalPoints < 150){ return "F"; } } function studentInfo(){ return "Student : " + this.lastName + "," + this.firstName + "<br>"+ "eMail : " + this.email + "<br>" + "Course ID : " + this.courseID + "<br>" + "--------------------------------" + "<br>" + this.assignments() + "--------------------------------" + "<br>" + "Total Points : " + this.totalPoints() + "<br>" + "Final Grade : " + this.finalGrade(); } function createStudents(){ var student1 = new Student("Jake", "Hennry", "jhennery@gmail.com","COIN-070B.01", ["Assignment1","Assignment2","Assignment3","Assignment4","Assignment5","MidTerm", "Final"], [25, 25, 28, 20, 29, 40, 40] ); alert("Student : " + student1.lastName + "," + student1.firstName + "\n"+ "eMail : " + student1.email + "\n" + "Course ID : " + student1.courseID + "\n" + "---------------------------------------" + "\n" + student1.assignments() + "\n" + "---------------------------------------" + "\n" + "Total Points : " + student1.totalPoints() + "\n" + "Final Grade : " + student1.finalGrade()); } var titleArray = ["Assignment1","Assignment2","Assignment3","Assignment4","Assignment5","MidTerm", "Final"]; var pointsArray = [30, 30, 28, 27, 29, 41, 45]; var student = new Student("Haripriyaa", "Ganesan", "haripriyaa@gmail.com","COIN-070B.01", titleArray, pointsArray ); </script> </head> <body> <script type="text/javascript"> document.writeln(student.toString()); </script> </body> </html> |