JavaScript - Calling A Variable Inside A Command
im not sure now to word it, or how to do it, im a php coder not a javascript -.-
but here it is, basicly i have one ajax file and wish to use it for everypage, i tryed to do it so i can just call one function for all ajax uses, but forms seem to be thowing me off the idea is when i call it, i stat if its a form or a element, Code: function ajax(str, b, c) { a = b; type = c; if (type === 'form') { document.form.b.value='Reading in progress...'; } if (type === 'element') { document.getElementById(a).innerHTML='Reading in progress...'; } xmlhttp = GetXmlHttpObject(); if (xmlhttp === null) { alert('Your browser does not support XMLHTTP!'); return; } xmlhttp.onreadystatechange = stateChanged; xmlhttp.open('GET', str, true); xmlhttp.send(null); } in this, the variable a is set as the id of the elemnt/form, it works fine for elemnts, but not for forms, i think this is because its thinking a is the id, not the variable, any way around this? Similar TutorialsHi, I have an embarrassingly similar problem to the last time I was here. I have a google map that generates links and checkboxes from an xml file and puts them in a sidebar. The links open infowindows and the checkboxes show or hide lines on the map. Which all works ok. But (like last time) I have another function that puts arrowheads along those lines to indicate directionality. The code which turns the lines off and on looks like this: Code: function togglePoly(poly_num) { if (document.getElementById('poly'+poly_num)) { if (document.getElementById('poly'+poly_num).checked) { gpolys[poly_num].show(); } else { gpolys[poly_num].hide(); } } } and the sidebar creation code is like this: Code: sidebar_html += '<input type="checkbox" id="poly'+poly_num+'" checked="checked" onclick="togglePoly('+poly_num+');">' + label + '<br />'; so I was thinking that I could just call the functions that put the arrows on the lines like this, to show/hide them along with their respective lines: Code: function togglePoly(poly_num,category) { if (document.getElementById('poly'+poly_num)) { if (document.getElementById('poly'+poly_num+category).checked) { gpolys[poly_num].show(); show(category); } else { gpolys[poly_num].hide(); hide(category); } } } and change the sidebar code to this: Code: sidebar_html += '<input type="checkbox" id="poly'+poly_num+'" checked="checked" onclick="togglePoly('+poly_num+','+category+');">' + label + '<br />'; and all would be well. But all is not well - I get an error saying that my category is not defined in the sidebar_html line. If you want to see it in action, here's without trying to toggle the arrows on and off: http://xelawho.com/map/busroutes2.htm and here's the version with the category undefined error: http://xelawho.com/map/busroutes3.htm can anybody help me out here? thanks in advance. How to set a js command using a variable? var name = 'field'; var number = '1'; name.number(); doesn't work [when the js function is called field1] I am using a set of dynamically created textareas and need to be able to reference each one by number. Any thoughts? I am modifying a small online text editor. I have a series of dynamically generated fields: sub0 sub1 sub2 etc. I get stuck feeding the modified data back. subX.selection.setContent() - where X is the field number. how can I set X as a variable? I don't know how I should do ? Quote: <html> <head> <script type="text/javascript"> function add(a,b){ y=a+b return y } var aaa = add(one,two) //one needs to get somehow get the value of yil, in this case 10 var one = function reas(){i=10;if(i<10){yil = 15}; else{yil = 10; yil = one;}; var two = 20; document.write(y) </script> </head> </html> also why doesn't this work? Quote: <html> <head> <script type="text/javascript"> function adder(a,b){ var k=a+b; return k } var hes=adder(5,kol); kol=40; alert(hes); </script> </head> </html> you cannot have variables in callback functions? I know I have a thread about the sorting function I'm about to post, but this problem doesn't deal with the sorting itself, but rather the fact that a variable is not passing. The code below is the relevant part to an autosuggest feature. The variable that isn't being passed is "firstValidIndex". It is being set appropriately, but when it is used in "sortArray()", its value is 0. Code: // here we must check to see if where the string matched was at the beginning of a string inside this.aNames // firstValidIndex is the first index where the char is at the beginning of a string var firstValidIndex; loop1: for(var j in firstIndices) { loop2: for(var k in allOccurrences) { if(allOccurrences[k] == firstIndices[j]) { firstValidIndex = firstIndices[j]; aList.push(this.aNames[i]); ctr++; break loop1; break loop2; } } } function sortArray(a,b) { var lca = a.toLowerCase(); var lcb = b.toLowerCase(); var lco = str.toLowerCase(); var diff = lca.indexOf(lco,firstValidIndex) - lcb.indexOf(lco,firstValidIndex); // some debugging code here alert("Comparing "+lca+" with "+ lcb+"\nDiff:"+diff+"\nFirst Valid Index: "+firstValidIndex); if ( diff < 0 ) return -1; if ( diff > 0 ) return 1; return 0; } aList.sort(sortArray); Hello everybody I have a problem with Java Script damned I want to add the values of several variables in one variable and then use this variable, which contains the values of variables You can see the following example HTML Code PHP Code: <input type="text" name="txt1" /> <br/>age <input type="text" name="txt2" /> <br/><br/> <input type="button" name="submits" value="send"/> Javascript Code PHP Code: field = document.getElementsByName('txt1')[0]; field2 = document.getElementsByName('txt2')[0]; submit = document.getElementsByName('submits')[0]; data = 'data=' + field.value + '&data2=' + field2.value + '&submits=' + submit.value; document.getElementsByName('submits')[0].onclick = function(){ alert(data); } After executing this code I find that the variables are not displayed values As in the following picture I want to know what the cause of this problem ? How can I call a PHP Function inside a Javascript Function? This is what I have so far, but I don't think I'm doing it the right way. Any suggestions? PHP Code: <?php function phpQuery(){ $query = mysql_query("INSERT INTO mytable VALUES('','name','email')"); } ?> <script type="text/javascript"> function delayQueries() { timeoutID = window.setTimeout(doQueries, 2000); } function doQueries() { var runQuery = "<?php phpQuery(); ?>"; } </script> Hi all, I have a set or icons that which over time I replace with a different icon and and add a onclick event to them. This is my code Code: function updateStatusIcons(retText) { updatingStatuses = true; var updates = retText.split("|"); for (z=0; z<updates.length; z++) { var sysId = trim(updates[z].split(":")[0]); var projectId = trim(updates[z].split(":")[1]); if (projectId != "") { var statusImg = getSysidsImg(sysId); statusImg.src = "images/tick.gif"; statusImg.className = "hand"; statusImg.title = "Project "+ projectId +" created, Click here to find in project search"; statusImg.onclick = function () { document.location = "projectSearch-FTTC.jsp?initAction=loadproject&projectId="+ projectId; }; // Remove sysid from csv removeSysidfFromCSL(sysId); } } if (pollingOn) { pollingupdate = setTimeout("checkForProjectComplete()", 5000); } updatingStatuses = false; if (runErrorFunction) { markErrors(); } } Everything works fine except for the onclick event. In the hover message of the icon, the correct project ID is displayed in the message, hoever in the function, the onclick funtion always loads the page with the last set project id. How can I pass the project id into the onclick function and make it stay fixed and not be the value of that it was last set to? TIA, Dale Hi, I am working on a google map where you can show lines on the map by checking checkboxes. Lines are displayed according to their category attribute in the xml file. The function that picks up the checkbox click is like this: Code: function boxclick(box,category) { if (box.checked) { show(category); } else { hide(category); } Another part of the code assigns that category attribute to arrows, so that when a line of "x" category is displayed, the relevant arrows are displayed along with it, to indicate directionality. I also have a select list which displays the lines by looping through their array and using selectedIndex in a function called handleSelected2. But I can't get the arrows to display along with the lines from the select box. After trying many, many things, I figure that all I need to do is to call the show(category) function from inside the handleSelected2 function and it should all come together. So I came up with this: Code: function handleSelected2(opt,category) { for (var h = 0; h <gpolylines.length; h++) { gpolylines[h].hide(); } h = opt.selectedIndex - 1; if (h > -1) { gpolylines[h].show(); } for (var v=0; v<pts.length; v++) { show(category); } } which gets me lines, but no arrows. You can see it sort of working he http://www.xelawho.com/map/zonesarrowstest.htm I figure I've got to be close, because if I just tell it to show all the arrows (without going through the category filter) like this: Code: function handleSelected2(opt,category) { for (var h = 0; h <gpolylines.length; h++) { gpolylines[h].hide(); } var h = opt.selectedIndex - 1; if (h > -1) { gpolylines[h].show(); } for (var i=0; i<pts.length; i++) { pts[i].show(); } } then all the arrows show up, as you can see he http://www.xelawho.com/map/zonesarrowstest2.htm I'm not getting any error messages and I've tried pretty much everything I can think of... I've been tweaking this for days and it's driving me crazy. Does anybody else have any ideas? Thanks in advance. Ok...so here is what I have: Code: function myClass() { this.checkLogin = function(name,pwd) { if(name.length > 0 && pwd.length > 0) { $.ajax({async: false, type: "post", url: "url", dataType: "json", data: "data", success: this.parseData}); } } this.parseData = function(data) { this.status = data.status; alert(this.status); } this.getStatus = function() { alert(this.status); } } Everything works above. The first alert shows that this.status was set to 'error'. However, if I call myClass.getStatus(), I get undefined. How can I get the parseData function to set the variables in the parent function? Thanks! hello im trying to change a variable set outside of a function and calling the function with an onchange... i'm having problems getting the variable to change Code: <script type="text/javascript"> var price = '<?php echo $price; ?>'; function addtwo() { if(document.add.size.value == "2xl") { price = price + 2; } } </script> Hi, Is is possible to access a global variable for use inside a function? Thanks for help in advance Mike Hey all! Got a question I can't seem to find an answer to. I have a little JS app that is a glorified calculator which I posted the code for below. My code uses the document object to replace the html in the "content" <div> and works great. However, I want to add an inline style in order to change the background of the input (readonly field with an id of "coutput") based on either of the global variables named "MJPD" or "IJPD", (depending on the switch case selected in the user prompt at the beginning of the script.) Simplified....if the value of MJPD is less than 4.6, I want the "coutput" field's background to be red, else be green. The same goes for IJPD, except the threshold for red will be <3.83. Code and what I have tried is below. After reading the code, look below it to see what I have tried and maybe tell me what I'm doing wrong! =) Any help is greatly appreciated.......I have spent a week searching for this little answer and I can't seem to find it! Code: <script language="JavaScript"> var MJPD = 1; var IJPD = 1; function sayhello(){ // *** live test for inline JS code placement alert("IT WORKS!!! Now change me =)"); } ////////////////////////////////////////////////////// function changeScreenSize(w,h) { window.resizeTo( w,h ) } /////////////////////////////////////////////////// function iJPDCalc(form) //calculate IJPD value { var ij = parseFloat(form.IJobs.value, 10); var it = parseFloat(form.ITime.value, 10); var IJPD = 0; IJPD = (ij / it) * 8.0; form.I_JPD.value = IJPD; } ///////////////////////////////////////////////////// function mJPDCalc(form) //calculate MJPD value { var mj = parseFloat(form.MJobs.value, 10); var mt = parseFloat(form.MTime.value, 10); var MJPD = 0; MJPD = (mj / mt) * 8.0; form.M_JPD.value = MJPD; } ///////////////////////////////////////////////////// function ijpdcolor() //set bg color of coutput based on IJPD's value { if (IJPD >= 3.83) { return ("green"); } else { return ("red"); } } ///////////////////////////////////////////////////// function mjpdcolor() //set bg color of coutput based on MJPD's value { if (MJPD >= 4.6) { return ("green"); } else { return ("red"); } } ///////////////////////////////////////////////////// function startVZT3(){ var n=0; n=prompt("What would you like to do? 1: Calculate IJPD 2: Calculate MJPD 3: Exit", "Enter a value from 1-3") switch(n) { case(n="1"): document.getElementById("content").innerHTML='<FORM><h2>Combined IJPD Calculator</h2><p>Install components completed today:</p><INPUT NAME="IJobs" VALUE="3.84" MAXLENGTH="10" SIZE=10><p>Hours taken to the jobs:</p><INPUT NAME="ITime" VALUE="8" MAXLENGTH="10" SIZE=10><h4> Click the button to calculate your IJPD:</h4><INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON class="cbutton" onClick=iJPDCalc(this.form)><p>Your current combined IJPD for today is:</p> <INPUT NAME="I_JPD" class="output" style=" " id="coutput" READONLY SIZE=10></FORM>'; break case(n="2"): document.getElementById("content").innerHTML='<FORM><h2>Combined MJPD Calculator</h2><p>Trouble components completed today:</p><INPUT NAME="MJobs" VALUE="4.6" MAXLENGTH="10" SIZE=10><p>Hours taken to the jobs:</p><INPUT NAME="MTime" VALUE="8" MAXLENGTH="10" SIZE=10><h4> Click the button to calculate your MJPD:</h4><INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON class="cbutton" onClick=mJPDCalc(this.form); mjpdcolor();><p>Your current combined MJPD for today is:</p> <INPUT NAME="M_JPD" class="output" style=" " id="coutput" READONLY SIZE=10></FORM>'; break case(n="3"): alert('This page will now close...'); window.close(); break default: document.getElementById("content").innerHTML='<h1 style="padding-top: 40px; color: red;">You need to enter a value! Please try again...</h1>'; break } } /////////////////////////////////////////////////////// </script> </head> <body onload="changeScreenSize(825,775)"> <div id="wrapper"> <div id="sub_wrapper"> <br /> <br /> <input type="button" class="button" onclick="startVZT3()" value="Start VZT3 Web!" /> <br /><br /> <div id="content"> <h3 style="padding-top:60px;">VZT3</h3> </div> </div> <script type="text/javascript"> <!-- trying script to ensure function and dynamic update of this value - doesnt work 2/3/2010 --> document.write(mjpdcolor()); </script> </div> </body> OK, so on the last line of each case statement where it injects html code into the content div, in this code style=" background: ** ** " and in between the ** ** marks, I have added such things as <script type="text/javascript">document.write(mjpdcolor())</script> (or ijpdcolor, depending on which case I am working with). Theoretically, this should pull the value of MJPD (or IJPD), evaluate it for the if statement, then return the value of red or green and set the value of the background dynamically - but of course it doesnt. I have also tried different inline styles and even adding the css id and trying to link it to the mjpdcolor() function, but all to no avail. Can someone help me please?? Thanks everyone, your awesome! hi all, I am fairly new to Javascript, and am trying to "print" a var inside a script. I have this piece of script, which loads images from a gallery: Code: $(document).ready(function(){ $('title').text('G3 Ajax Gallery'); loadGallery('/gallery3/rss/feed/gallery/album/114'); }); The number 114 defines what part of the gallery to be loaded. I would like to define this with a var, but dont know how to "print" it into the url. So: loadGallery('/gallery3/rss/feed/gallery/album/114'); woulkd become something like: loadGallery('/gallery3/rss/feed/gallery/album/my_var'); Any help would be much apreciated. Thanks, Sion. Reply With Quote 01-21-2015, 12:41 PM #2 xelawho View Profile View Forum Posts Senior Coder Join Date Nov 2010 Posts 3,043 Thanks 56 Thanked 568 Times in 565 Posts PHP Code: var myvar=114; // or however you are defining it loadGallery('/gallery3/rss/feed/gallery/album/' + myvar); Thank you in advance if someone can help. I have been banging my head against the wall for hours now. Here is the code: Code: for (var i = 0; i < BS_crm['activityTypes'].length; i++) { var clickFunc = function(){ activityList.showForm( -1, {blockType:[""+BS_crm['activityTypes'][i]['id'], "0"]} ); }; var type = { value: BS_crm['activityTypes'][i]['id'], label: "Add New "+BS_crm['activityTypes'][i]['label'], css: BS_crm['activityTypes'][i]['css']+"_16", onClick: clickFunc }; previewLinks.items.push( type ); } Now, basically what I am doing here is running through one array to create an array of objects, that will be used to create links that will use whatever onClick function I pass it. The problem is that on the second line I need the BS_crm['activityTypes'][i]['id'] to be a value, not a reference. If that line was simply changed to: Code: var clickFunc = function(){ activityList.showForm( -1, {blockType:["3", "0"]} ); }; then everything would work as I need. How can I make this happen? I would really appreciate any help. Thank you again in advance. Hello. Is there any way to get the variable name of an object from inside the object? E.g. PHP Code: function Bla(){ this.write = function(){ document.write(<objectname>); } } obj1 = new Bla(); obj1.write(); //Outputs obj1 Here is my script: PHP Code: function myTimer(seconds, obj){ this.seconds = seconds; this.obj = obj; this.startTimer = function(){ if(this.seconds>0){ this.seconds--; this.obj.innerHTML = this.seconds; this.timer = setTimeout("Timer.start()",1000); } } } Timer = new Timer(10, obj); Timer.startTimer(); Now the problem is that the variable that contains the object must be named "Timer". This way I cannot create new timer objects with different variable names I have tried: this.timer = setTimeout("this.start()",1000); but it doesn't work. That's why it would be good to detect the variable name and instead use something like this: this.timer = setTimeout(varname+".start()",1000); I would rather not have to pass the variable name through a parameter like this: Timer1 = new Timer(10, obj, "Timer1"); Thanks in advance. I am trying to use the LPR command inside a javascript to print a PDF file directly to the printer. Want just a simple webpage with a button which will print test.pdf when clicked. lpr -S xxx.xxx.xxx.xxx -P print -o l C:\Users\xxxxxx\Desktop\test.pdf I know very little when it comes to javascript. If you know of a better way to use the lpr command, please let me know. I need to set something up so every X amount of second on a page it goes a certain command, and keeps resetting the counter after everytime and goes again. I thought of many of the timer commands I have found on Google but didn't know if this was the RIGHT way to do it since I want it to be a document command that repeats. If what is returned to the command is true instead of false it needs to be able to change location of the browser, so I didn't know if the timer commands I found were right or not. Thanks. Sorry for the stupid question but i can't find a specific answer and i'm a newby. Here is a example of what i have: <html> <head> <script type="text/javascript"> function open_win() {window.open("http://www.microsoft.com","Window1","menubar=no,width=660,height=300,toolbar=no,scrollbars=yes");} </script> </head> <body> <form> <input type=button value="Open Window" onclick="open_win()"> </form> </body> In stead of a button to open one window, i would like a numeric input box that asks "How many windows do you want to open?" then incorporate a loop command to loop the open_win() x amount of times. Any help would be appreciated. Thanks Hi, I have this code.. Code: javascript:function showMore() {ProfileStream.getInstance().showMore(); setTimeout(showMore, 2000)}; showMore(); i want to loop it 10 times, but do not know how to do it. I have been told that the for var command is what I want, but I cannot get it to work. Any help would be appreciated. Thanks |