JavaScript - Passing Variable To A Function Inside A Function
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. Similar TutorialsHi, Any one help me In one variable i have some data ex: var data = document.getElementById("imageId").value; I want to pass this data to another function inside another function ex: var button1 = '<img src="images/Remove-button.gif" width="70" height="15" onclick="removeVerifyImageRow(this),saveLibData('+data+')"/>'; while running the application i am getting an error incase if the data is string ex:if data is 'image1' i am getting an error, but with number there is no problem ex: if data is '1122'. this is very urgent to solve this problem plz any one help me 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! 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 have a DOM click event that creates a <span>. When the user clicks a button, it turns that <span> into a textarea that the user can type a new name in, press enter, and then the span contains the text the user input. Sort of like when you rename a file in Windows Explorer. Anyway, the code is something like this, and I'm wondering if I can use 'area_el' in this way... right now it's giving me the error that area_el is undefined, even though I define it in the function that contains the Event declaration. The first part is the Dom stuff to make it all work. It's not stuff I need to mess with, but I'm putting it here in case it's useful. Code: var Dom = { get: function(el) { if (typeof el === 'string') return document.getElementById(el); else return el; }, add: function(el, dest) { var el = this.get(el); var dest = this.get(dest); dest.appendChild(el); }, remove: function(el) { var el = this.get(el); if(el.parentNode != null) el.parentNode.removeChild(el); } }; var Event = { add: function() { if (window.addEventListener) { return function(el, type, fn) { Dom.get(el).addEventListener(type, fn, false); }; } else if (window.attachEvent) { return function(el, type, fn) { var f = function() { fn.call(Dom.get(el), window.event); }; Dom.get(el).attachEvent('on' + type, f); }; } }() }; The following code defines what happens when the user clicks submit to create a polygon. I also have some variables: Code: var created_area_array = Array(); var createdarea_index = 0; var number_of_areas_saved=0; var currently_renaming=false; Event.add(window, 'load', function() { Event.add('SubmitArea', 'click', function() { if(polyPoints.length>0) add_created_area(); }); }); Finally, where the issue is. I define area_el in the function below, and further down I want to pass it to a function within the "rename" click event, but I get an error that area_el is undefined. Code: function add_created_area() { number_of_areas_saved++; var area_el = document.createElement('span'); var area_el_remove = document.createElement('span'); var area_el_rename = document.createElement('span'); var new_entry = polyPoints; var new_entry_array_index = "Area" + (createdarea_index); var new_entry_array_name = "Area #" + (createdarea_index+1); area_el.innerHTML = '<span class=\"address-text\">' + new_entry_array_name + '</span><br>'; area_el_remove.innerHTML = "<a onMouseOver=\"rollover('address_remove')\" onMouseOut=\"rollout('address_remove')\" style='cursor:pointer;'>" + "<img src=\"images/tabs-icons/normal-address_remove.png\" name='address_remove' title='remove' alt='remove'></a> "; area_el_rename.innerHTML = "<a onMouseOver=\"rollover('area_rename')\" onMouseOut=\"rollout('area_rename')\" style='cursor:pointer;'>" + "<img src=\"images/tabs-icons/normal-area_rename.png\" name='area_rename' title='rename' alt='rename'></a> "; created_area_array[new_entry_array_index] = new_entry; createdarea_index++; Dom.add(area_el_remove, 'CreatedAreas'); Dom.add(area_el_rename, 'CreatedAreas'); Dom.add(area_el, 'CreatedAreas'); Event.add(area_el, 'click', function(e) { if(!currently_renaming) { polyPoints = []; var thePolyPoints = (created_area_array[new_entry_array_index]).toString(); alert(thePolyPoints); //formatting created_area_array[new_entry_array_index] to store as polygon points in the polyPoints array thePolyPoints = thePolyPoints.replace(/[\[\]{}]/g, ""); thePolyPoints = thePolyPoints.replace(/Location/g, ""); //adding the co-ordinates to the polyPoints array thePolyPoints = thePolyPoints.split(","); for(var ctr=0; ctr+1<thePolyPoints.length; ctr+=2) { var location1 = new Microsoft.Maps.Location(thePolyPoints[ctr],thePolyPoints[ctr+1]); polyPoints.push(location1); } var out=""; for(var i=0; i<polyPoints.length; i++) { out += polyPoints[i] + " "; } alert(out); //creating the polygon and searching... if(create_area==true) { drawPolygon(); polygonSearch(); } else if(create_area==false) { document.getElementById('createarea').innerHTML = "<a id='createarea'><span class='create_area' style='color:blue'><strong>Create Area</strong></span></a>"; document.getElementById("mapDiv").oncontextmenu = function(){return false} MouseUpHandlerId = Microsoft.Maps.Events.addHandler(map, "mouseup",MouseUpHandler); MouseDownHandlerId = Microsoft.Maps.Events.addHandler(map, "mousedown",MouseDownHandler); MouseMoveHandlerId = Microsoft.Maps.Events.addHandler(map, "mousemove",MouseMoveHandler); MouseOverHandlerId = Microsoft.Maps.Events.addHandler(map, "mouseover",MouseOverHandler); drawPolygon(); polygonSearch(); create_area=true; } } }); Event.add(area_el_remove, 'click', function(e) { Dom.remove(this); Dom.remove(area_el_rename); Dom.remove(area_el); if(number_of_areas_saved>1) number_of_areas_saved--; }); Event.add(area_el_rename, 'click', function(e) { if(!currently_renaming) { area_el.innerHTML = '<textarea name=\"renaming_area\" id=\"renaming_area\" style=\"width:200px;height:10px;background-color:#DCDCDC; resize:none;font-size:8px;\" onKeyPress=\"return enter_rename(area_el, event)\" maxlength=\"30\"></textarea><br>'; currently_renaming=true; } }); Event.add("createdarea_clear", 'click', function(e) { Dom.remove(area_el_remove); Dom.remove(area_el_rename); Dom.remove(area_el); created_area_array = []; number_of_areas_saved=0; createdarea_index=0; }); } The enter_rename(area_el, event) function that isn't passing in my variable. Code: function enter_rename(area_el, event) { var keyPressed = (event.which) ? event.which : event.keyCode; var current_str = document.getElementById("renaming_area").value; if(keyPressed == 13) { if(current_str.length>0) { if(allSpaces(current_str)==true) { alert("Please enter a meaningful area name."); return false; } else { area_el.innerHTML = '<span class=\"address-text\">' + current_str + '</span><br>'; currently_renaming=false; return true; } } else return false; } else return true; } Making area_el global does not clear the span elements when I click my "createdarea_clear" button, however when it's local, the function works as expected. Every time i click on one of the said elements, it puts "undefined" into the textbox each time i click on an element. it seems to me that the Key_Table[x] is not getting passed correctly. How do i make sure that this is getting passed correctly? Here's my Code: Code: <script type='text/javascript'> // Startup Script if (document.addEventListener) { document.addEventListener("DOMContentLoaded", LoadEventListeners, false); } function LoadEventListeners() { var Key_Table = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"]; // Create event Listeners for the alphabetic keys for(var x = 0; x < Key_Table.length; x++) { Key_Table[x] = document.getElementById(Key_Table[x]); Key_Table[x].addEventListener("click", function(){ InsertChar(Key_Table[x]); }, false); } } function InsertChar(Char) { alert("Char is:" + Char); // Textbox data document.getElementById('TextData').value = document.getElementById('TextData').value + Char; } </script> I'm trying to make it so when you click a cell in a table it runs a function based on the value within that cell. With the current code, no matter what cell is clicked, the alert box displays the same number, which is the last number in my array. The variable, princ, is just being overwritten rather than writing code to each the cell with the proper value. Help is appreciated. Thanks. Code: for(i=0;i<=3;i++){ document.writeln('<tr>'); document.writeln('<th>'+(periodArray[i])+'</th>'); for(j=0;j<=2;j++){ princ = principleArray[j][i]; document.writeln('<td onclick="(calculateInterest(princ,1,1))">$'+principleArray[j][i]+'</td>'); } document.writeln('</tr>'); } function calculateInterest(principle,rate,period){ totalInterest = principle * rate * period; totalLoanCost = principle + totalInterest; alert('Total Interest: '+totalInterest+'\n'+'Total Loan Cost: '+totalLoanCost); } 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? 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 This code is finally working, but for some reason no matter which button i click on, it is always returning "9". It should be firing the alert(x), where x is the x index value for that particular addEventListener Code: .addEventListener('click', function (e) {alert(x);}, Code: <html> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', DOMLoadedEventFunction, false); function DOMLoadedEventFunction () { for(var x = 0; x < 9; x++) { document.getElementById('btn' + x).addEventListener('click', function (e) {alert(x);}, false); } } </script> <body> <input type="button" id="btn0" value="1"> <input type="button" id="btn1" value="2"> <input type="button" id="btn2" value="3"> <input type="button" id="btn3" value="4"> <input type="button" id="btn4" value="5"> <input type="button" id="btn5" value="6"> <input type="button" id="btn6" value="7"> <input type="button" id="btn7" value="8"> <input type="button" id="btn8" value="9"> <input type="button" id="btn9" value="10"> </body> </html> This is just some sample code that i will later turn into an HTML5 File Manager 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! Hi, Is is possible to access a global variable for use inside a function? Thanks for help in advance Mike 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, I am facing a problem in passing replace() function as an argument in user defined java function, can any one help me how to resolve it? intention is to pass a file path to my user defined function, but before passing the path i want to replace the character '\' to '\\' I am posting my javascript function he <a href="#" onclick="OpenDocPreview('<%# Eval("PATH")%>'.replace(/\\/g,"\\\\"), '<%# Eval("Filename")%>')"><%# Eval("DocTitle") %></a> function OpenDocPreview(url, docname) { alert('message from search base : ' + url + ' ' + docname); } thank you, 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, 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. Hi, I want to pass a javascript function's return value, to an anchor tag's href parameter i.e. <a href> Suppose I have a function called getTrackingCode( ) that contains a value "testSite" Code: <script language = "JavaScript"> function getTrackingCode( ) { return "testSite"; } </script> Now I want to pass this function's value to anchor's href, I have attempted these: Code: 1. <a href="http://www.helloworld.com/?id=" + getTrackingCode( )> 2. <a href="javascript: document.location= 'http://www.helloworld.com/?id=' + getTrackingCode( );"> So that the resulting URL becomes http://www.helloworld.com/?id=testSite But none of the procedures work. Please help me do it. NOTE: Please note that I can't use the function with document.write to write the whole tag because that would be very hard to manage as I will have to use it in case of text links, image links, hotspots etc. and for each I would have to write a separate function. Furthermore, I don't want the Status bar of the browsers to show something like javascript:location.href (); etc. I want the actual href link to be seen in the Status bar, as if no javascript manupulation is done. In a nutshell, the code should be reusable for the href paramater in anchor tag's href of any element, be it a text link, image link, script link, hotspot or link area and doesn't show javascript function calling in the Status bar of the browser. I've heard that I can do such a thing using ElementbyID etc. but have no idea. Please help me with this, Thanks much! How do I pass an id to a function?? Or is this even possible. Code: <html> <head> <title> JavaScript array passing example </title> <script type="text/javascript"> function init(){ display(addText1); display(addText2); display(addText3); display(addText4); } function display(var myText){ var newText = '<h2>' + "Will this change anything..." + '</h2>'; document.getElementById('myText').innerHTML = newText; } </script> </head> <body onload="init()"> <div id="addText1"></div> <div id="addText2"></div> <div id="addText3"></div> <div id="addText4"></div> </body> </html> 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 Hi, I was wondering if i can pass my php variables through javascript function. Actually i have a simple table of pictures, when clicked in the picture a new popup page comes up, it working fine uptill this stage but now i want to pass a value through it, for instance if user clicks on picture1 then my popup url should be "item_large.php?id=pic1 My Javascript junction for the popup window: Code: function popup() { window.open("item_large.php","Register","menubar=no,width=500,height=400,toolbar=no"); } My Html code where i have my pictures: Code: <td height="19" align="center" valign="top" onmouseover="this.bgColor='#CC3300' ; this.style.cursor='pointer'" onmouseout="this.bgColor='#FFFFFF'" <A HREF="javascript:popup()">Picture01</A> </td> Thanks I am trying to pass a value to another function, seems to work with the other function i have but not this one? any reasons why this wont work? Code: /* ---------------------------- */ /* XMLHTTPRequest Enable */ /* ---------------------------- */ function createObject() { var request_type; var browser = navigator.appName; if(browser == "Microsoft Internet Explorer"){ request_type = new ActiveXObject("Microsoft.XMLHTTP"); }else{ request_type = new XMLHttpRequest(); } return request_type; } var http = createObject(); /* -------------------------- */ /* SEARCH */ /* -------------------------- */ function autosuggest(q,f,r) { alert(q+' '+f+' '+r); // q = document.getElementById(var f).value; // // Set te random number to add to URL request nocache = Math.random(); http.open('get', 'ajax_search_for_airport.php?q='+q+'&f'+f+'&r'+r+'&nocache = '+nocache); http.onreadystatechange = autosuggestReply(r); /* this line is not working as expected, it kicks up an error Message: Type mismatch Line: 26 Char: 1 Code: 0 i am wanting to pas the value of r to the other function. */ http.send(null); } function autosuggestReply(r) { if(http.readyState == 4){ var response = http.responseText; e = document.getElementById(r); if(response!=""){ e.innerHTML=response; e.style.display="block"; } else { e.style.display="none"; } } } function fill(r,fieldid,resultsid) { e = document.getElementById(fieldid); e.value=r; document.getElementById(resultsid).style.display="none"; } |