JavaScript - Passing To A Function
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> Similar TutorialsHi, 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, 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. Hi, 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 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! 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! 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'm trying to trigger a function when the user clicks on an image. The function will test for whether a variable passed to it is empty or not and branch accordingly. The image has an <a href> behind it that triggers the function OK, but I cant seem to pass a variable to the function. The variable contains a value from a database field, and I think it is probably a syntax thing because if I set the variable to contain a string instead (i.e. b = 'this works') within the <a href> it works OK. So the problem may be with setting the variable to contain the database field value within the <a href> Hope that makes sense, here's the code: [ICODE] "<center><a href=""javascript:void(null)"" onClick=""goConfirm(b);"" b = ""<%=RS(8)%>;"" title=""Get map (open new window or tab)"" ><IMG src=""images/bt_compass.gif"" border=""0"" /></center></a>" [ICODE] goConfirm is the function b is the variable I'm trying to pass RS(8) is the database field Many thanks 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 found a simple script, and I'm trying to customize it just a hair to accept the ID, and I'm doing something wrong. Evidently, I'm completely useless at JS Code: There is <span id="id1234" style="visibility: hidden">NOT </span>hidden content here. <script type="text/javascript"> function showIt(uniqueID) { document.getElementById(uniqueID).style.visibility = "visible"; } setTimeout("showIt(id1234)", 2000); // after 2 sec's </script> I want to be able to pass the ID in when I call the function. How would do that? 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 would like to pass an array to a function but how does the program know which array I would like to choose from?? Lets say I have 3 arrays and I would like to pass array C, to my function. I checked the web but they only show if you have ONLY 1 array but NOT for multiple arrays. How would I even go about doing this?? Code: var arrA=new Array("fox.com","nbc.com","abc.com", "google.com"); var arrB=new Array("car","bike","boat", "plane"); var arrC=new Array("1","2","3", "4", "5", "6", "7", "8", "9"); function display(myArray){ myArray[1] = "changed"; } display(myArray); document.writeln(myArray[1]); thanks Hello I am trying to call a javascript autocomplete function but I want to use a variable instead of an input field ID So this is my fuction: Code: $(function() { $("#tags").autocomplete({ source: "search.php?field=field1" }); }); <p><b>Field:</b><input type="text" input id = "tags" name="field1" size="60" ><br> Basically I want to use the same function for numerous input fields, so how can I pass a var instead of the input id ? Any help would be appreciated 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"; } I'm new to javascript and have come across what I'm sure its a really easy problem to solve. I want a page with a hyperlink that passes a variable to another 'pop-up' page (in this case a name, its just an example) and new pop-up page prints a message followed by the variable thats passed. Here is the code as it is right now Code: <html> <head> <script language="javascript" type="text/javascript"> function popitup(a) { var reply = 'a'; newwindow=window.open('','name','height=200,width=150'); var tmp = newwindow.document; tmp.write('<html><head><title>popup</title>'); tmp.write('</head><body><p>"Hello there" + reply </p>'); tmp.write('<p><a href="javascript:self.close()">close</a> the popup.</p>'); tmp.write('</body></html>'); tmp.close(); } </script> </head> <body> <a href="testpopup.html" onclick="popitup('Toby')" >Link to popup</a> </body> </html> In short, I just want the pop-up page to print 'Hello there Toby' or whatever name I choose to pass across. Any help much appreciated!! The 'testpopup.html' url is just the initial webpage. Hello, I am trying to execute a javascript function passed as argument. I am not sure of the exact way to do it. <html> <head> <script type="text/javascript"> var checkLink = function(linkId, enabledFunction){ var linkidObj = document.getElementById(linkId); if(linkidObj.className=="activelinktext" ) { enabledFunction(); return false; } else if(linkidObj.className=="inactivelinktext") { return false; } alert("*inside CheckLink*"+enabledFunction); }; </script> </head> <body> <a class="inactivelinktext" onclick="checklink(this,"javascript:goback();")"> </body> </html> Thanks, -Vijay Hello there, I was having some trouble with 2D arrays (or array of arrays). Essentially, the array has 100 rows, with two columns. The first column of every row holds a name, and the second holds a sales amount. With the use of a do while loop, the user can continuously add up to 100 names and sales amounts. After all the information the user wishes to add is stored into the 2D array I'm attempting to pass that very same 2D array as a parameter to a function called printRow as can be seen in the code below: Note: the function call and the actual function are found in two separate javascripts. Code: var salesPerson=new Array(100) for (i=0; i <=100; i++) { salesPerson[i]=new Array(2); } var x = 0; do { salesPerson[x][0] = getName(); salesPerson[x][1] = getSales(); x++; }while(x != 100 && confirm("Enter more employee information?")); printRow(salesPerson[][]); Code: function getName() { var nameEntered = prompt("What is your first name?"); return nameEntered; } function getSales() { var error; var salesEntered; do { salesEntered = prompt("What were your sales?"); error = false; if (isNaN(salesEntered) || salesEntered == null || salesEntered == "") error = true; }while(error); return salesEntered; } function printRow(salesPerson[][]) { for (i =0; i<salesPerson.length; i++) { document.write(salesPerson[i][0] + " " + salesPerson[i][1]); } } At the moment I'm only looking to print the contents of the 2D array that I pass as a parameter to the document. As is, the javascipt doesn't seem to execute at all, it worked fine up until I added the printRow function call and function which leads me to believe I may not be passing it as a parameter correctly. Any tips on how to do this correctly would be greatly appreciated! 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. Hi, I am quite new to javascript but I'm quite sure this problem is very easy to solve. I have a vague idea of what might be going wrong but I have no idea what I should be doing instead. Here is what I'm trying to do: User inputs X and Y coordinates into form validate that they are numbers do a little bit of maths redirect to a php script with a single variable tacked onto the end of the url Here is the form code: Code: //part of a larger php script to make the form echo "<form name='gotoForm' onsubmit='return coordCalc()'> <fieldset> <legend>Go to Square</legend> X <input type='text' id='X' size='1' maxlength='3'/> Y <input type='text' id='Y' size='1' maxlength='3'/> <input type='submit' value='Go To' /> </fieldset> </form> "; which references these functions in the header: Code: //Is it a number function isNumeric(elem, helperMsg){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } //deal with the input, check if they are both numbers with the above function //if they are do some maths on the input //add the result onto a url and redirect function coordCalc (){ var Xcoord = document.getElementById('X'); var Ycoord = document.getElementById('Y'); if(isNumeric(Xcoord, "Please enter a Number for X")){ if(isNumeric(Ycoord, "Please enter a Number for Y")){ //Takes the X and Y coordinates and transforms them into a single number //not fully coded in case you try putting some numbers into the formula btw :) var X = parseInt(document.getElementById('X').value); var Y = parseInt(document.getElementById('Y').value); var G = 16; var Z = (((G + 1) - Y) - Y); var A = (Y + Z); var B = (X - 1); var L = ((A * (G - 1)) + B); window.location = "map.php?start=" + L; } } return false; } The number validation works but the url ends up as map.php?start=NaN. Now, this simply must be the way I am assigning the Xcoord and Ycoord variables with the document.getElementByID() function I am sure. But like I said, I have no idea what to do instead, any help is massively appreciated. Thankyou! 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> 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> window.onload = function(){h = parseInt(document.getElementById( "div1" ).style.height);} var t; function addHeight(openAccordionID){ clearInterval(t); document.getElementById(openAccordionID).style.height = h+"px"; h+=1; t = setInterval("addHeight('"+openAccordionID+"')",10); for(var x=1; x<h; x++) if(h%(x*100)==0){clearInterval(t);} } </script> </head> <body> <div id="div1" onclick="addHeight(this.id)" style="width: 200px; height: 20px; background-color: yellow;">Increase Height</div> </body> </html> How can I still use the parameter "openAccordionID" in the blue-highlighted part? I tried, but it failed. |