JavaScript - Javascript Function Not Returning String
Hi everyone,
I have a hunch that my function is not returning the string value. Below runs some information about the code: getvalues_2() - A function that recognizes the value of the string selected by the user from the drop down list and sends it to a variable. Variable name is 'groom_profession' here. Based on the value (text) returned, it assigns a particular number to the variable 'profession' in this case. But, I have been noticing that irrespective of the value chosen from the drop down list, the variable 'profession' is assigned a default value from the switch case statement. I know the variable (textval_2) is able to store the correct value from the drop down list with the help of an alert command. But, it fails while returning the value. I even tried initializing the string in the function body but to no avail. What could be wrong here? Following is the code for one of the drop-down lists: Code: <b> Groom's current Profession </b> <FORM NAME="Profession"> <SELECT NAME="Groomprofession" onchange = "getvalues_2()"> <OPTION VALUE="c1">Select </OPTION> <OPTION VALUE="c2">Doctor </OPTION> <OPTION VALUE="c3">Engineer </OPTION> <OPTION VALUE="c4">Lawyer </OPTION> <OPTION VALUE="c5">CA </OPTION> <OPTION VALUE="c6">IAS </OPTION> <OPTION VALUE="c7">Engineer + MBA </OPTION> <OPTION VALUE="c8">Family Business </OPTION> <OPTION VALUE="c9">None of the above </OPTION> </SELECT> </FORM> Following is the code for function getvalues_2() declaration: Code: <script type = "text/javascript"> function getvalues_2() { var val_2 = document.Profession.Groomprofession.value; var si_2 = document.Profession.Groomprofession.selectedIndex; if (si_2 != 0) { var textval_2 = " "; textval_2 = document.Profession.Groomprofession.options[si_2].text; //alert (val_2); // for testing //alert (textval_2); // for testing return (textval_2); } } </script> Following is the code for the switch case statement: Code: <script type="text/javascript"> var profession; groom_profession = getvalues_2(); switch(groom_profession) { case "Engineer" : profession = 1.8; break; case "Doctor" : profession = 1.9; break; case "Lawyer" : profession = 1.65; break; case "CA" : profession = 1.7; break; case "IAS" : profession = 2.0; break; case "Family Business" : profession = 1.5; break; case "Engineer + MBA" : profession = 1.95; break; case "None of the above" : profession = 1.95; break; default: profession = 0.6; } </script> The website has a total of 11 drop-down lists (so 11 functions like getvalues, and 11 switch case statements. I thought if I could get one to work, the others might follow suit too). I would be really grateful if someone could look into my problem and suggest where I am going wrong. Thanks a lot! Similar TutorialsHey guys..... My skill level on JavaScript is only intermediate so maybe this is really obvious.... but it's driving me nuts & I can't work it out. Heres some example code.. Code: function createAJAXobject() { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { /* alert("Cannot create object in IE."); */} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { /* alert("Cannot create object in IE."); */} try { return new XMLHttpRequest(); } catch(e) { /* alert("Cannot create object in Mozilla."); */} alert("XMLHttpRequest is not supported."); return null; } function ajaxRequest(url) { // Create AJAX object var myAJAX = createAJAXobject(); // Retrieve data myAJAX.open("GET",url,true); myAJAX.onreadystatechange = function() { // Was it a success? if (myAJAX.readyState < 4) { return false; } // Set results var res = myAJAX.responseText; /* Returns results */ if (res != '') { return res; // Correctly enters this part via testing // Output of the variable 'res' here outputs correct text } else { return false; } } myAJAX.send(null); } function searchCats(text) { // Set URL for ajax request var url = 'search_cats.php?search_text='+text; // Set up element we're modifying var results = document.getElementById('cat_list'); // Send the request var ajaxResponse = ajaxRequest(url); alert(ajaxResponse); // = undefined } I have included comments in the above explaining my problems..... the data is correct when I use alert() just before I return it, but when I use alert inside the function that calls it I get "undefined" & the error in FireFox says "ajaxResponse" is undefined. Please please someone help! Hey all, I have a simple example below showing how when I pass in the value of the value attribute of option node, and then use if operator to check whether parameter is a string or not, even though it's a string, it converts it to false boolean and triggers the else statement rather than calling a function: Code: <body> <select> <option value="createMsg">Add Message</option> <option value="removeMsg">Remove Message</option> </select> </body> Code: var menu = { handleMenu : function(callback){ if(callback === "string"){ menu[callback](); } else { console.log("Issue occurred") } }, createMsg : function(){ var content = document.createTextNode("Please give additional information."), heading = document.createElement("h1"); heading.appendChild(content); document.body.appendChild(heading); }, removeMsg : function(){ } } document.getElementsByTagName('select')[0].onchange = function(){ menu.handleMenu(this.value)}; callback should be a string so why is it saying otherwise? Thanks for response I am wondering how can I return the variable senttext from the function below? I have declared it and when I alert(senttext) below it appears as I want it but I need to return it and pass it to another function. When I change alert() to return the variable becomes undefined??? var senttext; function getData() { if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open('GET',"http://www.site6.certcoordering1.com/Download/recall.txt" ); req.onreadystatechange = function() { if (req.readyState == 4) { if (req.status == 200) { senttext ='<table style="border:thin black solid"><tr><td><h2>Recent</h2></td><td><h2>Recalls</h2></td><td></td><td></td></tr>' ; var ad2 = req.responseText.split("\n"); for(i=0; i<ad2.length-1; i++) { // now split by comma var ad3 = ad2[i].split(","); senttext += '<tr><td><p>'+ad3[0]+'</p></td><td> <a href="http://www.site6.certcoordering1.com/Download/'+ad3[2]+' rel="nofollow" target="_blank">'+ad3[1] +'</a></td><td></td></tr>' } senttext += '</table>' ; alert(senttext); // I need to return senttext, not alert! When I send it it becomes undefined? } else { alert('File did not load correctly.'); } } } req.send(""); } I find it odd that this function is returning the day as 1, when it is clearly the 28th. when I run the code the answer I get looks like this: 1-Feb-2011 9:27 Code: function getDateTime(when) { var theDate = new Date(); var day = theDate.getDay(); var month = theDate.getMonth(); var year = theDate.getFullYear(); var myTimeArr = theDate.toTimeString().split(":"); var monthNumber = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") when.value = day + "-" + monthNumber[month] + "-" + year + " " + myTimeArr[0] + ":" + myTimeArr[1]; any advice? I have a function where in I call another function that assigns a value to a var. e.g. Code: function setVar{ var thisVar = 'hello'; return thisVar; } function callFuncSetVar { var newVar = setVar(); alert(newVar); } For some reason my code below is returning 'undefined'. But when I place an alert(); before the 'return' it shows the correct value. However when I place an alert(); to show the var that is set to what the function returns it says 'undefined'. Firebug throws no errors. I am using a little bit of jQuery. Scenario: Client Side : Simple functions that have events tied to different elements. Each time an event is triggered the function begins an Ajax call to an external server side page filled with JS functions. Server Side : Our client side AJAX call sends the name of the function we want to call out on this file. Once called and performed, it returns DOM edits that could be fired once our client side page receives the data back from Ajax. I know that data being returned from Ajax is always a string. But would it be possible? I mean could the server side file send out commands or rather DOM edits that the client side could pick up on and perform? I am almost 100% certain the answer is no due to JS needing to be cached in the browser and what not, but I figured I would ask the experts anyways. BTW: objective is to move sensitive core JS functions to prevent online application theft... without Flex or Air. Hello everyone, I am creating a small application for my memory book. I want to have one of those calendars like in Here .. that would retutn values like: day month year - seperatelly that I could use in php. Im looking for easy solution if there is one.. Simple and short script Kind regards, Aurimas Here is a clip of code from a script project im working on. Now my document.getElementsByTagName is returning a "undefined" value. Can anyone tell me whats wrong with my code? Code: <a href="http://www.anotherrandomsite.com" style="text-decoration: none; color: #EDDBAF; font-size: 16px;"> <center style="margin-left: 10px; margin-right: 10px;"> <font style="color: #EDDBAF; font-size: 16px;" id="title"></font> </center> </a> <li id="name"><a http="http://www.randomsite.com" style="color: blue;">John Doe</a></li> <script type="text/javascript"> var pname = document.getElementById('name').getElementsByTagName('a'); //now if i remove the ".getElementsByTagName('a')" it will actually work, but it also includes the <a> tag thats within the <li> tag, which i dont want. document.getElementById('title').innerHTML=pname.innerHTML; </script> is there a function in JS to remove a string from some text but without using the replace function? I am removing a specific string from my text using and using the replace function of the match text with a non breaking space but what i really do not want to add anything to my html. The replace is been place in a visual editor box after the user adds text and save the form, this is the code i am using to replace the code, i am using a regular expression to look for <META content="MSHTML 6.00.6000.16890" name="GENERATOR"><LINK title="/iw/ewebeditpro20/ektnormal.css" href="/iw/ewebeditpro20/ektnormal.css" rel="stylesheet"> : // Pass 1 - Removes extra code checks on Regular Expression inside replace function var newstrchanged = strEscaped.replace(/^%26%2365279%3B%20%3CMETA%20content%3D%22MSHTML%20.+.stylesheet%22%3E/g, ''); Hi, I'm just wandering, how can you stop the replace() function from replacing characters inside a word, such as, if I try to replace 'x' with 'and', then my string would go from 'example, x' to 'eandample, and'. Thanks in advanced How can I call a function in javascript like: Code: var x = string.Length ??? and not like: Code: var x = Length(string); (just for arguments sake) (Also please don't suggest JQuery, I'm doing this to learn!) Thanks! 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, Hello, When I run the following code, the .Length function returns "undefined." Please help! This is driving me crazy. Code: var strTest = 'test'; alert(strTest.Length); Using the typeof function, I know that JS is treating the variable as a string. Any suggestions? Hey everyone, I wanted to write my own script for a fade-in animation, since the ones I have found have got too many options or need some framework, which makes them unnecessarily big. I wanted to learn too. Unfortunately, the code didn't work as I wanted, and I commented some things so as to find out what's happening. The only function called from outside is fadeIn with a string as argument (in the example, this string is: d1296668690535). This is the code: Code: var fadems = 500; // Anim. duration in milliseconds var fps = 20; // Frames per second function fadeIn(elemId){ var frames = fadems/1000 * fps; var delay = 1000 / fps; var incrOp = 1 / frames; //document.getElementById(elemId).style.zoom = '1'; setOp(elemId, 0); for(i=1; i<=frames; i++){ debugOutLn("(fadeIn for) elemId = " + elemId); setTimeout("setOp(" + elemId + "," + incrOp*i + ")", delay*i); } } function setOp(elemId, val){ debugOutLn("(setOp) elemId = " + elemId + "; val = " + val); // document.getElementById(elemId).style.opacity = val; // document.getElementById(elemId).style.filter = 'alpha(opacity = ' + val * 100 + ')'; } Code: function debugOutLn(str){ document.getElementById("debug").innerHTML += str + "<br />"; } And this is the text it outputs (on Opera 11.01): Code: (setOp) elemId = d1296668690535; val = 0 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (setOp) elemId = [object HTMLDivElement] ; val = 0.1 (setOp) elemId = [object HTMLDivElement] ; val = 0.2 (setOp) elemId = [object HTMLDivElement] ; val = 0.30000000000000004 (setOp) elemId = [object HTMLDivElement] ; val = 0.4 (setOp) elemId = [object HTMLDivElement] ; val = 0.5 (setOp) elemId = [object HTMLDivElement] ; val = 0.6000000000000001 (setOp) elemId = [object HTMLDivElement] ; val = 0.7 (setOp) elemId = [object HTMLDivElement] ; val = 0.8 (setOp) elemId = [object HTMLDivElement] ; val = 0.9 (setOp) elemId = [object HTMLDivElement] ; val = 1 Why is an object reference assigned to what was previously a string? Thanks for the help! I made a mouseover event of a caption on a picture, when I hover the opacity of the background color of the hover and the text goes down. What I want is that when I hover over the image which the caption is floating on, the onmouseover event gets activite. For an imaginary example: Code: function unhighlight(x) { x.style.backgroundColor="transparent" } Function ActivationFuction() { activate.function="unhighlight" } thanks 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> How to handle String in Javascript
Hello, I have the following Javascript function: Code: function loadReviews(){ var url='http://search.twitter.com/search.json?callback=?&q=test'; jQuery.getJSON(url,function(json){ jQuery.each(json.results,function(i,review){ jQuery("#divroller_container").append('<div class="reviews" id=item'+i+'>'+review.text+'<br>Reviewed By: '+review.from_user+'</div>'); }); start(30000, 1); }); } I'm trying to use this in a PHP page. I tried to make do an echo ' and then display the Javascript but I'm struggling on how to convert the following line to PHP to that it still works like it should in Javascript: Code: jQuery("#divroller_container").append('<div class="reviews" id=item'+i+'>'+review.text+'<br>Reviewed By: '+review.from_user+'</div>'); I still need the Javascript variables to function the same etc. Any help would be greatly appreciated. Thanks in advance! Hi everyone, I am pretty new at javascript OOP. I have a javascript file that has plenty of javascript functions, variables, arrays, etc. I need to convert this into an object. Here is an example: Code: var myvar1 = ''; var myvar2 = new array(); var myvar3 = new array(); var myvar4; var myvar5 = 60; var myvar6 = ''; function myfunc1(){ myvar1 = 'hello'; return myvar1; } function myfunc2(somenum=0){ myvar5 = somenum; //calling myfunc1() from within this function. //do something in here } function myfunc3(){ //calling myfunc1() from within this function. for(i=0;i<somelength;i++){ myvar2 = myvar3[i]; (something to put into the array) } } 1. I need to create an object and put ALL the varibles (myvar1 - myvar5) in that object. 2. Then the first two functions "myfunc1 and myfunc2" inside the same object. 2. And the function myfunc3 needs to sit OUTSIDE my object as a regular javascript function. It calls on myfunc1 (which is inside the object) and also inserts data into myvar2 (which is classified inside the object) and myvar3 (which is classified inside the object as well). This is what i came up with, but it's not going well: Code: var myobj1 = function(){ this.myvar1 = ''; this.myvar2 = new array(); this.myvar3 = new array(); this.myvar4; this.myvar5 = 60; this.myvar6 = ''; var myfunc1 = function(){ this.myvar1 = 'hello'; return this.myvar1; } var myfunc2 = function(somenum=0;){ this.myvar5 = somenum; //calling this.myfunc1() from within this function. //do something in here } } function myfunc3(){ //calling mynewobj.myfunc1() from within this function. for(i=0;i<somelength;i++){ mynewobj.myvar2 = mynewobj.myvar3[i]; (something to put into the array) } } var mynewobj = myobj1; HELP.....!!!! i really want to get into object oriented world, so thanks in advance. |