JavaScript - Passing Return Value To Function
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 Similar TutorialsI need to get this script to work, I only included what im having the problem with. I am Using jQuery Library. Here is how this should work: .btnRoof div is clicked the parent id is retrieved as var pid a function called roof is called which simply changes a css background to "color" the function perform is called to get the "color1[0]" from the array. My Problem: perform() returns the word color1, color10, color1[0], or c. instead of images/cp-roof-blue.png as listed in the array. Code: $(document).ready(function() { var color1=new Array(); color1[0]="images/cp-roof-blue.png"; color1[1]="images/cp-panel-blue.png"; color1[2]="images/cp-trim-blue.png"; function perform(name, x) { alert(name[x]); //alert([name][x]); //alert(name+'['+x+']'); //alert(color1[0]); // correct return name[x]; } function Roof(color) { $("#colorPicker .roof").css("background", "url("+color+")"); } $('.btnRoof').click(function() { var pid = $(this).parent().parent().attr("id"); Roof(perform(pid, 0)); }); }); I tried to clarify as much as possible, please let me know if I need explain further. Thanks. I have a project that uses and Ajax call but it appears that the call back function cannot take arguments, nor return values. However, I have wrapped another function inside the call back function that takes xmlhttp.responseText as the argument and returns values that are supposed to be placed in a global array. If I do, for instance: callback function code.... globalArray = someFunction(xmlhttp.responseText) alert(globalArray), I get the expected values. but a function is called later to query the contents of the global array the global array is empty (No other code or functions exist in this project to alter the global array) Primary dev client is FireFox 3x on Mac OSX Is this a bug, or is there some other aspect of javascript that I need to know about? I am using ajax here because javascript does not have an array shuffling function and php does. So I send an array to the server, have it shuffled by the server and returned to the requesting page. I'm trying to "progressively enhance" one of my surveys using javascript. Basically, I have rating scales that make use of radio buttons as each point on the scale. Each radio button occupies its own cell in a table. I wrote some functions that will highlight cells on mouseover in a color corresponding to its position on the scale (e.g. the lowest point is red, the midpoint is yellow, the highest point is green). When a radio button is clicked, the background of the button's cell and preceding cells in the same row will be colored accordingly. The functions are working well in FireFox and Chrome (I just have to add a few lines using the addEvent function to make it compatible with IE). The effect looks a lot nicer when I add a function that makes the visibility of the radio buttons hidden. However, I want to make sure that there is a fallback option in case the functions that color the cells don't work for whatever reason. I would not want the radio buttons hidden in this case. Is there a method whereby I can call the "hideRadiobuttons" function only if the other functions are successfully executed? 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, 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 don't understand about the jquery basic example the code is below PHP Code: <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $('p').addClass(function(n){ return 'par_' + n; }); }); }); </script> <style type="text/css"> .par_0 { color:blue; } .par_1 { color:red; } </style> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button>Add classes to p elements</button> </body> </html> i want to understand about the how is work function(n){ in the function a and how work return function return 'par_' + n; thanks mate I'm looking for some assistance. I'm trying to write a javascript to validate a form for a class. When I try to submit the form with none of the fields filled in , it goes to the intercept page without showing any errors. In addition to this, I have an error message. Return is outside of function. I have NO clue what they mean here, or what I've done wrong. Could someone take a look and give me an opinion? Enclosed is the entire javascript and the top portion of the related form. <!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> <script type="text/javascript"> <!-- Hides script from older browsers --> "function validate()" { if(document.form2.size.value=="Please Choose") { alert("Did you forget to select a size?"); return false; } if(document.form2.quantity.value=="Please Choose") { alert("How many did you want??"); return false; } if(document.form2.email.value=="") { alert("Please enter your Email Address.."); return false; } if(document.form2.verify.value=="") { alert("Could you enter it again please.."); return false; } if(document.form2.verify.value!=document.form2.email.value) { alert("The Email Addresses do not match"); return false; } if(document.form2.email.value.match((/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/)) { alert("Email address was not valid please RETRY"); return false; } else return true; } //--> </script> <form id="form2" name="form2" method="post" onSubmit="return validate(this)" action="2intercept.asp"> <table width="150" border="0" cellpadding="0"> <tr> <td><div align="right"> <label for="size">Size Desired:</label> </div></td> <td><div align="left"> <select name="size" id="size"> <option selected="selected">Please Choose</option> <option value="4x6">4x6</option> <option value="5x7">5x7</option> <option value="8x10">8x10</option> </select> </div></td> </tr> <tr> <td><div align="right"></div> <label for="quantity">Quantity Desired</label></td> <td><div align="left"> <select name="quantity" id="quantity"> <option>Please Choose</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5+">5+</option> </select> </div></td> ANY advice, corrections or suggestions would be GREATLY appreciated.. I'm at my wits end with this stuff. My function the_magnitude() takes in values from 4 different asp:textboxes. The textboxes "easting" and "northing" contain numbers that don't change, but the textboxes "east" and "north" contain numbers inputed by the user, and the function returns "error" as a value to be put into another textbox that we'll call "error box". So what it's suppose to do is when I update the information in either "east" or"north" it will update, on change, the number in the "error box". It kinda works. My problem is that if the number is a value that changes the style to red, #ff0000, in the function it wont update the "error box" and it just leaves a red zero that is a default number in the box. The only way I can get the number to change is if I end up with a number less than 200, which would make the text green. I'm pretty sure it's a problem with my javascript. here is my function Code: <script type="text/javascript"> function the_magnitude(easting, east, northing, north, error) { var a = easting.value; var b = east.value; var c = northing.value; var d = north.value; var total = Math.sqrt(((a - b) * (a - b)) + ((c - d) * (c - d))); if (total > 200) { document.getElementById('TextBox155').style.color = "#ff0000"; document.getElementById('TextBox155').style.fontWeight = "bold"; } else { document.getElementById('TextBox155').style.color = "#008000"; document.getElementById('TextBox155').style.fontWeight = "bold"; error.value = roundNumber(total); } } </script> and here are the two buttons that I input numbers into for east and north Code: <html> <body> <asp:TextBox ID="TextBox153" runat="server" Height="0.25in" Style="font-family: Arial, Helvetica, sans-serif; font-size: small; text-align: center" Width="0.75in" onchange="the_magnitude(document.getElementById('TextBox153'), document.getElementById('TextBox212'), document.getElementById('TextBox154'), document.getElementById('TextBox213'), document.getElementById('TextBox155'))" ></asp:TextBox> </body> </html> Code: <html> <body> <asp:TextBox ID="TextBox153" runat="server" Height="0.25in" Style="font-family: Arial, Helvetica, sans-serif; font-size: small; text-align: center" Width="0.75in" onchange="the_magnitude(document.getElementById('TextBox153'), document.getElementById('TextBox212'), document.getElementById('TextBox154'), document.getElementById('TextBox213'), document.getElementById('TextBox155'))" ></asp:TextBox> </body> </html> and here is the textbox that I want the return of the function to go into. Code: <html> <body> <asp:TextBox ID="TextBox155" runat="server" Height="0.25in" Style="font-family: Arial, Helvetica, sans-serif; font-size: small; text-align: center" Width="0.5in">0</asp:TextBox> </body> </html> Yesterday I started looking into clientside database handling with html5 and localstorage. I've been trying for hours to make a function like the one below, but I can't figure out how to return the name variable. Any ideas? Code: function hent_kontakt_navn(var1, var2) { var db = MYDB; db.transaction(function (tx) { tx.executeSql('SELECT * FROM db_kontakter WHERE field1=\'' + var1 + '\' AND field2=\'' + var2 + '\' LIMIT 1', [], function (tx, results) { var len = results.rows.length, i; for (i = 0; i < len; i++){ var fornavn = results.rows.item(i).fornavn; var etternavn = results.rows.item(i).etternavn; var navn = fornavn + ' ' + etternavn; alert(navn); //This works and alerts the correct value } }, null); }); return navn; //But this one returns undefined. I know variables don't pass like this between functions, but how can I make it work so that the function returns this var? } I am trying to figure out that if the function "xmlhttp.onreadystatechange=function()" returns true the whole function "function checkUser(str)" should return true as well....so not sure how to do it. i have banged my head since long so please advise! Here is the code below: -------------------------------------------------------- function checkUser(str) { var sp = document.getElementById("msgs"); if (str=="") { document.getElementById("msgs").innerHTML="Username cannot be empty."; return false; } if (str.length <= 6) { document.getElementById("msgs").innerHTML="Username cannot be less than 6 characters and must not start with a number or a special value"; return false; } if (window.XMLHttpRequest) { //code for IE7+, firefox, chrome, opera, safari xmlhttp=new XMLHttpRequest(); } else { //code for old IE xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { if (xmlhttp.responseText === 'FOUND') { sp.style.color = "red"; sp.innerHTML = "[ERROR]: The username \"" + str + "\" already exist. Please try a different name."; return false; } else if (xmlhttp.responseText === 'NOT FOUND') { sp.style.color = "blue"; sp.innerHTML = "Username: VALID"; return true; } } } xmlhttp.open("GET", "checkUser.php?q="+str,true); xmlhttp.send(); } Ok, guys. I'm new to JavaScript, so go easy. I'll be asking bunches of "dumb" questions for a while. 1st question, and the only one for now ... Say I have the following function: Code: function SwapValues(SwapVal1,SwapVal2) { TempSwapVal=SwapVal1; SwapVal1=SwapVal2; SwapVal2=TempSwapVal; } I don't care about the return value of the function itself, but I do need the new values of SwapVal1 and SwapVal2. In ASP when I do this, the values get returned. How do I get this to work in JS? Good morning Guru's and Experts, I really need your help with this one. It seems that the function this_week('end') is returning a bad date of 12/33/2014 (mm/dd/yyyy) where it should properly read: 01/02/2015 Code: function this_week(x) { var today, todayNumber, fridayNumber, sundayNumber, monday, friday; today = new Date(); todayNumber = today.getDay(); mondayNumber = 1 - todayNumber; fridayNumber = 5 - todayNumber; if (x === 'start') { //var start_dd = today.getDate() + mondayNumber var start_dd = today.getDate() var start_mm = today.getMonth() + 1 var start_yyyy = today.getFullYear() return start_mm + '/' + start_dd + '/' + start_yyyy } if (x === 'end') { var end_dd = today.getDate() + fridayNumber var end_mm = today.getMonth() + 1 var end_yyyy = today.getFullYear() return end_mm + '/' + end_dd + '/' + end_yyyy } } Reply With Quote 12-29-2014, 07:43 PM #2 Philip M View Profile View Forum Posts Supreme Master coder! Join Date Jun 2002 Location London, England Posts 18,371 Thanks 204 Thanked 2,573 Times in 2,551 Posts I understand that you are trying to get the date next Friday. Try this script:- Code: <span id = "info"></span> <script type = "text/javascript"> var curr = new Date(); // get current date var first = curr.getUTCDate() - curr.getUTCDay(); // First day is the day of the month - the day of the week var last = first + 5; // last day is the first day + 5 = Friday var lastday = new Date(curr.setDate(last)); var yy = lastday.getUTCFullYear(); var mth = lastday.getUTCMonth()+1; if (mth<10) {mth = "0" + mth} var dy = lastday.getUTCDate(); if (dy<10) {dy = "0" + dy} // now manipulate the display of year,month,date as desired var result = mth + "/" + dy + "/" + yy; document.getElementById("info").innerHTML = "Week Ending Friday " + result; </script> Lottery: A tax on people who are bad at math. Hi All, I have a button in my html form that will process some functions when user clicks on the button. The problem is after processing the functions, the result is not displayed in the form where I want it to be displayed. I want to ask whether we can create table in the function and display the result in the table row/column but in the same form. Is this possible to be done? And how to do this? In this form cpiM, the input button will call function showIndex. Code: <tr> <td><input type="button" value="Enter" onclick="showIndex(document.cpiM.currFrom.options.selectedIndex, document.cpiM.currTo.options.selectedIndex, document.cpiM.base.options.selectedIndex, document.cpiM.country.options.selectedIndex)"> </td> <td><input type="button" onclick="frmResetM()" value="Reset form" /> </td> </tr> In this function, I want to display the result of calcIndex right below the button Enter in the form cpiM. Code: function showIndex(frm, to, base, country) { for (i=frm; i<=to; i++) { document.write(calcIndex(i, base, country)); document.write("<br/>"); } } Hi All, This is in ASP.Net Im creating a task loggin system and this allows the user to raise tasks and update them, im using javascript for validation and if the fields are empty it then changes the fields back ground to Red which is fine but then it goes on to update the data in SQL which i dont want, any suggestions or how i can achieve no post back is the result from the function is False (for fields in error) Html Code where im calling the function Code: <asp:button runat="server" id="btnChangeCommentsAuth" CSSclass="RaiseButton" OnClientClick="CommentsCheck('MainDisplayContentChange_txtAuthCommentsArea');" PostBackUrl="~/RaiseTaskChange.aspx" Text="Auth" /> Javascript function Code: function CommentsCheck(comments) { var com; var result = new boolean(); com = document.getElementById(comments); if (document.getElementById(comments).value == '') { com.style.backgroundColor = "#B20635"; result = 0; } else { result = 1 } } Thanks in Advance look forward to your reply. 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> 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! |