JavaScript - Callback Variable Needs To Get A Variable Inside A Function
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? Similar TutorialsHi 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 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. 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 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 ? 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? 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 there, Sorry that the title of this is not very descriptive but I really don't know how to describe what it is i am after. I have a variable that contains an image source. (well I hope it does) Code: var imagebackground = (this.parentNode.parentNode.parentNode.childNodes[1].childNodes[0]).src; Now I need that variable to spit out the image source into where it says background, but wrapped in a url( ) Code: $jQ(document).ready(function(){ $jQ(".btn-cart").click(function(){ $jQ('#floater').animate_from_to('.block-cart', { pixels_per_second: 200, initial_css: { background: (THIS IS WHERE I WANT IT) } }); $jQ(this).attr('id', ''); $jQ(this.parentNode.parentNode.parentNode.childNodes[1].childNodes[0]).attr('id', ''); }); }); So basically if the variable was to equal - http://www.google.co.uk/image.jpg - it would function like: Code: $jQ(document).ready(function(){ $jQ(".btn-cart").click(function(){ $jQ('#floater').animate_from_to('.block-cart', { pixels_per_second: 200, initial_css: { background: url(http://www.google.co.uk/image.jpg) } }); $jQ(this).attr('id', ''); $jQ(this.parentNode.parentNode.parentNode.childNodes[1].childNodes[0]).attr('id', ''); }); }); I hope I have provided enough information for someone to assist me with this, but if i havent then please tell me and i will try and explain some more. Cheers, Chris Example: Function First() { Var = x1 <--- Use this variable } Function Second() { Var = x2 Var = x1 + x2 } I know this is not the way in the example...but just making sure you know what im talking about. Hi I'm trying to get a variable named 'html' from one function and use it in another. My JavaScript knowledge is limited, so will be grateful for any help Please see code below Code: function createMarker(point, name, label, address, type) { var marker = new LabeledMarker(point, {icon: customIcons[type], labelText: label, labelOffset: new GSize(-6, -10)}); markerGroups[type].push(marker); GEvent.addListener(marker, 'click', function() {GEvent.trigger(map,"click",null,point,point); var html = '<div>LatLng:' + name + '</div><a href="javascript:void(0)" onclick="javascript:map.getInfoWindow().maximize()">more info.. </a>'; marker.openMaxContentTabsHtml(html); }); return marker; } // need to get html variable from the above function into this one below GEvent.addListener(map, 'click', function(ov, latlng, ovll) { if (latlng) { var regular = '<div id="sum">LatLng:' + latlng + '</div><a href="javascript:void(0)" onclick="javascript:map.getInfoWindow().maximize()">more info.. </a>'; var summary = '<div id="sum">Address of' + latlng + '</div><a href="javascript:void(0)" onclick="javascript:map.getInfoWindow().restore()">less info.. </a>'; var panoDiv = document.createElement('div'); panoDiv.width = "400px"; // can be anything, will be auto resized panoDiv.height = "200px"; var tabs = [new MaxContentTab('address', '<div id="address"></div>'), new MaxContentTab('streetview', panoDiv)]; map.openMaxContentTabsHtml(latlng, regular, summary, tabs, { maxTitle: "More Information", selectedTab: 'address',// or use index 1, style: { tabOff: { backgroundColor: '#CCCCFF' } },maximized: document.getElementById('maximized').checked }); } }); Hi all, I need to pass a variable to an inner function and I got it to work but: (1) I don't know why it works (2) I don't know if it's right or optimal So, please look and comment: Code: for (var h = 1.0; h <= 3.0; h += 0.5) { ed.settings.formats['spacing' + String(h.toFixed(1))] = { 'block' : 'p', 'styles' : { 'marginBottom' : String((h - 1).toFixed(1)) + 'em' } } h = (function (h) { c.onRenderMenu.add(function (c, m) { m.add({ 'title': String(h.toFixed(1)), 'caption' : 'Set the line spacing to ' + String(h.toFixed(1)), 'onclick': function () { ed.formatter.apply('spacing' + this.title); return false; } }).setDisabled(false); }); return h; })(h); }; You can ignore a lot of the code as it doesn't factor into the question... and I know that re-ordering the code can eliminate my problem (but I can't re-order it because defining the formats MUST come before "renderMenu" or else it doesn't work - and I don't want to use two loops - one to define the formats and another to define the menu). The part that's freaking me out is this: Code: h = (function (h) { c.onRenderMenu.add(function (c, m) { m.add({ 'title': String(h.toFixed(1)), 'caption' : 'Set the line spacing to ' + String(h.toFixed(1)), 'onclick': function () { ed.formatter.apply('spacing' + this.title); return false; } }).setDisabled(false); }); return h; })(h); See the strange things I have to do to get h inside of c.onRenderMenu.add()? Is this right? Can I do it any "better" or more correctly? Thanks! -- Roger Is there any way of running a function where the name is stored as a string in a variable? I mean, the same way that PHP handles this is by appending "()" to the end of the variable. Hi, I am having trouble passing the correct id to change the innerHTML. I have a jsp that display people and their address information. There could be several people in the list, so it is in a loop. That part all works good. There is a drop down list with countries in them. Based on the country they select, I want to change some of the text. Here is what I have: Code: <tr> <td class="datashaded" valign="top"><font size="2"><b>Country:</b></font></td> <td class="datashaded" valign="top"> <select tabindex="<%=countryTab%>" name="<%=country%>" size=1" onChange="changeText(this.form.<%=country%>, this.form.<%=addressLabel%>, this.form.<%=zipLabel%>);"> <% for (int i =0; i < countryList.size(); i++ ) { String countryOption = (String)countryList.get(i); String countryVal = bene.getAddress().getCountry(); String selected = ""; if ( countryOption.equalsIgnoreCase( countryVal ) ) selected = "selected"; %> <option value="<%=countryOption %>" <%=selected%> ><%=countryOption%></option> <% } %> </select> </td> </tr> <tr> <td class="datashaded"><div id="addr1"><font size=2><b id="<%=addressLabel%>">Address:</b></font></div></td> <td class="datashaded"> <input size=20 maxlength="50" tabindex="<%=add1Tab%>" name="<%=address1%>" value="<%=address1Value%>" </td> </tr> Everytime through the loop, addressLabel has an index added to it so it is unique - so I can refer to each person separately. Here is the js function: Code: function changeText(sel, txtField1, txtField2) { var selectedValue = sel[sel.selectedIndex].value; if ( selectedValue == "<%=IParticipantConstants.BENEFICIARY_COUNTRY %>") { document.getElementById(txtField1).innerHTML = 'Address:'; document.getElementById(txtField2).innerHTML = 'Zip:'; } else { document.getElementById(txtField1).innerHTML = 'Street or P.O. Box'; document.getElementById((txtField2).innerHTML = 'Postal Code:'; } } When I hardcoded the id= value, not matter which group I changed the country on, only the first one was changing, so I knew I needed unique ids for each group. There is more to the table, but this is the good part. When the onChange fires now, Nothing at all happens. Can anyone see the problem?? Thanks for looking! Hi, I know there are several ways to do this- but which way is best practice? I can access a variable from one function by making it a global variable, but I read that this isn't the most ideal way, and is a last resort. So for example if I have this: Code: function num1(){ var firstNum = 35; return firstNum; } function num2(){ var secNum = 52; return secNum; } function addNums(x,y){ var f = num1(x); var s = num2(y); var total = f + s; alert(total); } Then I call this function with a button. Now, I know this works, but it doesn't seem like a very good way to do what I'm after. Or is it? Any help/ tips would be great. edit: The idea is that the functions won't just return a single value and that's it. They will return a users choice in a given scenario, so they might return the user's age from the first function, then their location in the next etc etc, then I want to use this information in a separate function. I have a function which is currently called twice on the same page. Part of the function is to apply an onkeyup event to a created element. The problem is that when the function is called twice the first created element calls the onkeyup function of the second element! table_JD.length-1 = 0 for first element table_JD.length-1 = 1 for second element updateSearch_TC_JD(1) is somehow called from first element! Code: newSearchBox.onkeyup = function() {updateSearch_TC_JD(table_JD.length-1)} Thanks for any help you can provide! How do I store how many Windows my house has as a variable as this script I made isn't working. Quote: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script type="text/javascript"> var test function show_prompt(a_bac) { prompt(a_bac) } function show_alert(a_baf) { alert(a_baf) } </script> <body> <!-- How do I store how many Windows my house has as a variable? --> <input type="button" value="click" onclick="var theanswer = prompt('How many windows does your house have?')" /> <input type="button" value="answer" onclick="alert(theanswer)" /> </body> </html> Hi, I have a programing problem that have been around for ages. I have search on google using several expressions and words and after hours of digging i'm still unable to do it. I would like to get a value from a HTML page hosted remotely with an inconstant value. Then define this value and name as a javascript variable and apply or show in my page. Thanks for all the help P.S. Is there any way to make a domain lookup in javascript? I mean a user enters a domain and the script converts to an ip and shows to the user. If not thanks, probably it can only be done in the server side... 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. Here's something that I tested without the PHP and it worked ok. Now that I've introduced the PHP to the document it doesn't work. The PHP variable is not passing to Javascript properly. By use of some cleverly placed alert boxes, I figured out that the only thing that is getting passed forward is something called : "object HTML ImageElement" Specifically, I assign the element ID the unique ID number of the record in the SQL database. The problem isn't with the ID numbers themselves: They are alphanumeric and unique. I think it boils down to one of two lines of code. Either this isn't working (about line 12) Code: function expander(RecordID){ or perhaps it is when I am calling the function (about line 66): Code: echo "<img id='".$row['IDNumber']."' src=".$row['ImagePath']." width='5%' onMouseOver='expander(".$row['IDNumber'].");' onMouseOut='shrinker(".$row['IDNumber'].");'>";} The PHP works (I can get the images to appear, so the connection to SQL and such isn't a problem). I am sure most of the JavaScript is good, too, as I said I had it all working prior to dropping in the PHP. Since I am not going from JavaScript to PHP I don't think I need AJAX. I just need the PHP to pass to JavaScript. Any ideas? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="class.css" /> <script type = "text/javascript" language="javascript"> //<![CDATA[ var maxheight = 150; var countShrink = 1; function expander(RecordID){ var countGrow = 1; var pic = document.getElementById(RecordID); if(pic){ var imageh = pic.height; var imagew = pic.width; if(imageh<100){ countGrow++; imageh = imageh*1.2; imagew = imagew*1.2; pic.style.height = imageh + "px"; pic.style.width = imagew + "px"; var timer = window.setTimeout(function(){expander(RecordID);},2);} } else {alert("error on");} } function shrinker(RecordID){ var pic = document.getElementById(RecordID); if(pic){var counter = 1 var imageh = pic.height; var imagew = pic.width; if(imageh>20){ imageh = imageh/1.2; imagew = imagew/1.2; pic.style.height = imageh + "px"; pic.style.width = imagew + "px"; var timer = window.setTimeout(function(){shrinker(RecordID);},3);} } else {alert("error off");} } //]]> </script> </head> <body> <?php include('menuSub.html'); require_once('connect.php'); $idnum = 'phmdv06tbu'; //$q="SELECT * FROM art WHERE IDNumber = '".$idnum."'"; $q="SELECT * FROM art ORDER BY IDNumber LIMIT 4"; $r = @mysqli_query ($dbc, $q); echo "<div class='bodyContent'><div class='imageContent'>"; if($r){ while ($row = mysqli_fetch_array($r,MYSQLI_ASSOC)){ echo "<img id='".$row['IDNumber']."' src=".$row['ImagePath']." width='5%' onMouseOver='expander(".$row['IDNumber'].");' onMouseOut='shrinker(".$row['IDNumber'].");'>";} } else{ echo '<div class="bodyContent"> Error<div>'; } echo "</div></div>"; mysqli_close($dbc); ?> </body> </html> |