JavaScript - Call Function Only If Another Function Does Not Return Error?
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? Similar Tutorialsi keep getting error Call to undefined function codeandurl() below is my code PHP Code: <?php $value= strip_tags(get_field('link',$post)); $resultid=get_field('resultid',$post); codeandurl($resultid,$value); ?> <div id="result"></div> <script type="text/javascript"> function codeandurl(resultid,url){ $( "#result" ).text(resultid); $( "#result" ).dialog({ modal: true, buttons: { Ok: function() { $( this ).dialog( "close" ); } } }); window.open(url); return false; } </script> Hi, The Problem I get a error message only in IE when ever I try to call a function from an external file. I am using jQuery if that makes any difference and various plugins. Quote: Error: The value of the property '<function name>' is null or undefined, not a Function object. All the call work fine in FF, chrome, safari etc but for some reason I just can't get it to work with IE. This is getting annoying now, i have no idea what is causing it. here is an example: admin.js Code: function create_cleditor_admin_form(textarea_object) { $(textarea_object).cleditor({ height: 120, controls: // controls to add to the toolbar "bold italic underline | color highlight removeformat | bullets numbering | alignleft center alignright justify | undo redo | ", useCSS: false }); } calling code Code: $(document).ready(function() { try { create_cleditor_admin_form('textarea'); } catch(e) { alert("Error: "+e.message); } }); I have tried searching for this error on google and came up empty handed, surely it just something very stupid. Thanks in advance Hi all, I have written the following javascript code which makes a simple calculation and writes between the <span> tags using Inner HTML My code is: Code: <html> <head> <script type="text/javascript"> function hesapla() { kredimiktari = document.hesapla.miktar.value kredivadesi = document.hesapla.vade.value; faiz = document.hesapla.faiz.value; ayliktaksit1 = (kredimiktari * faiz) / kredivadesi; geriodeme1 = kredimiktari * faiz; document.getElementById('ayliktaksit').innerHTML = "<strong>Taksit / Ay :</strong>" + ayliktaksit1; document.getElementById('geriodeme').innerHTML = "<strong>Taksit / Ay :</strong>" + geriodeme1; } </script> </head> <body> <form name="hesapla"> <input type="text" name="miktar" value="Kredi Miktarı" onfocus = "if (this.value == 'Kredi Miktarı') this.value = '';" onblur = "if (this.value == '') this.value = 'Kredi Miktarı';" /> <input type="text" name="vade" value="Kredi Vadesi" onfocus = "if (this.value == 'Kredi Vadesi') this.value = '';" onblur = "if (this.value == '') this.value = 'Kredi Vadesi';" /> <input type="text" name="faiz" value="Faiz Oranı" onfocus = "if (this.value == 'Faiz Oranı') this.value = '';" onblur = "if (this.value == '') this.value = 'Faiz Oranı';" /> <div id="gosterim"><span id="ayliktaksit"></span><span id="geriodeme"></span></div> <input type='button' value='Hesapla' onClick='hesapla()'><br><br> <img src="images/dot2.png" width="180" height="2" alt="dot"/> </form> </body> </html> I am really confused as similar code on Tizag web site works fine. Code: <script type="text/javascript"> function changeText(){ document.getElementById('boldStuff').innerHTML = 'Fred Flinstone'; } </script> <p>Welcome to the site <b id='boldStuff'>dude</b> </p> <input type='button' onclick='changeText()' value='Change Text'/> Could anyone tell me what the wrong thing is about my code Many thanks in advance telmessos Eagle eyes needed! I have a function which is called twice. It allows the elements of an array to be set to a different color, successively: Code: function ln8 (arrayA,color,current) { var arrayB=(typeof arrayA == 'string')? arrayA.split(',') : arrayA; var line = document.getElementById(arrayB[current]); line.style.color = color; if (current != arrayB.length - 1) { current++; setTimeout(function() {ln8(arrayB, color, current)},8) } } It works fine the first call; the second time, FF throws an error message: 'line is null' referring to 'line.style.color = color;'. It's used in a switch function, and I've tested each case of the switch, two browsers, and still get the error. So I'm assuming the second call is the problem, but I just can't see what's wrong with it. Maybe before you wade through the code, can you think of other reasons for the error? First call: the function is at the third line of each case: Code: function makeLine5() { var a = Coin1() var b = Coin2() var c = Coin3() var h = ( a + b + c ) A=a;B=b;C=c;D=h; switch(h) { case 6: noHex2(5,'D'); noHex(Hex5Yang,'hidden',0); nodot(5, 4, 'e'); setTimeout('report5()',3000); setTimeout('ln8(Line5Yin,\'#e11\',0)',6000); setTimeout('dot(5, 4, \'f\')',10000); return false; break case 7: noHex2(5,'D'); noHex(Hex5Yin,'hidden',0); setTimeout('report5()',3000); setTimeout('ln8(Line5Yang,\'#e11\',0)',6000); return false; break case 8: noHex2(5,'C'); noHex(Hex5Yang,'hidden',0); setTimeout('report5()',3000); setTimeout('ln8(Line5Yin,\'#e11\',0)',6000); return false; break default: noHex2(5,'C'); noHex(Hex5Yin,'hidden',0);nodot(5, 4, 'f'); setTimeout('report5()',3000); setTimeout('ln8(Line5Yang,\'#e11\',0)',6000); setTimeout('dot(5, 4, \'e\')',10000); return false; } } second call: Code: function makeLine6() { var a = Coin1() var b = Coin2() var c = Coin3() var k = ( a + b + c ) A=a;B=b;C=c;D=k; switch(k) { case 6: noHex2(6,'D'); noHex(Hex6Yang,'hidden',0);nodot(6, 5, 'e'); setTimeout('report6()',3000); setTimeout('ln8(Line6Yin,\'#e11\')',6000); setTimeout('dot(6, 5, \'f\')',10000); setTimeout('lastBitz()',13000); return false; break case 7: noHex2(6,'D'); noHex(Hex6Yin,'hidden',0); setTimeout('report6()',3000); setTimeout('ln8(Line6Yang,\'#e11\')',6000); setTimeout('lastBitz()',13000); return false; break case 8: noHex2(6,'C'); noHex(Hex6Yang,'hidden',0); setTimeout('report6()',3000); setTimeout('ln8(Line6Yin,\'#e11\')',6000); setTimeout('lastBitz()',13000); return false; break default: noHex2(6,'C'); noHex(Hex6Yin,'hidden',0);nodot(6, 5, 'f'); setTimeout('report6()',3000); setTimeout('ln8(Line6Yang,\'#e11\')',6000); setTimeout('dot(6, 5, \'e\')',10000); setTimeout('lastBitz()',13000); return false;} } I know I shouldn't be having this problem at this stage. But what have I done wrong? I have my main page, I have my onload page and in that onload page I call a function: And then I get the error message: Fatal error: Call to undefined function OpenChat() The main page code (I've cut out the irrelevant scripts); Code: <?php session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] !='')){ header ("Location: Welcome.php"); } $Sfullname=$_SESSION['fullname']; $SMyPId=$_SESSION['MyPId']; ?> <!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"> <html> <title></title> <head> <script type="text/javascript"> function OpenChat(Msg){ loadgetdiv(); document.getElementById('<?php echo $Newdiv; ?>').style.display="block"; loadChatComplex('<?php echo $NewThisFile; ?>','<?php echo $Newdiv; ?>',Msg); } </script> <script type="text/javascript"> function loadChatCheck(File,ID,Tile,TID){ loadQuickCheck(File,ID); dodo = setInterval(function(){loadQuickCheck(Tile,TID)},5000); } </script> <script type="text/javascript"> function loadQuickCheck(File,ID){ if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById(ID).innerHTML=xmlhttp.responseText; malaky = setInterval(function(){loadQuickCheck(File,ID)},20000); } } xmlhttp.open("POST",File,true); xmlhttp.send(); } </script> </head> <body onload="loadChatCheck('getCheckNewMessages.php','txtHintCheckNewMessage','getFriendsOnline.php','txtHintShowFriends')"> <div class="mainpage"> <?php include("headermenu.php"); ?> <div id="txtHintShowFriends"></div> <div id="txtHintCheckNewMessage"></div> <br /><br /> </body> </html> AND the onload/getCheckNewMessages.php is PHP Code: <?php session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] !='')){ header ("Location: Welcome.php"); } $SMyPId=$_SESSION['MyPId']; include("dbconnect.php"); $result = mysql_query("SELECT COUNT(*) as newchat FROM chat WHERE chattee='{$SMyPId}' AND stat='new'"); $row = mysql_fetch_assoc($result); $total=$row['newchat']; echo 'This is ' . $total .'<br />'; if ($total >=1){ $result = mysql_query("SELECT * FROM chat WHERE chattee='{$SMyPId}' AND stat='new'"); while($row = mysql_fetch_array($result)){ $doormouse=$doormouse . ';' . $row['ChatID']; } $listees=explode(';',$doormouse); foreach($listees as $listor){ echo 'This is ' . $listor . '<br />'; $result = mysql_query("SELECT * FROM chat INNER JOIN allusers ON chat.chatter=allusers.PId WHERE chat.ChatID='{$listor}' "); while($row = mysql_fetch_array($result)){ echo "{$SMyPId};{$row['chatter']};{$row['fullname']};{$row['ref']}"; } echo $battlebox . '<br />'; $steptoe=OpenChat($battlebox); } $sql="UPDATE chat set stat='' WHERE ChatID='{$chatID}' "; mysql_query($sql,$con) or die(mysql_error()); } ?> Needless to say I am trying to create an instant chat. <p> <script type="text/javascript">// <![CDATA[ var metrics = { "mm" : 1, "cm" : 10, "m" : 1000, "inch" : 25.4, "foot" : 304.8 }; function convert(num, dec){ var val = document.getElementById("fromVal").value; if(isNaN(val)){ return } function roundNumber(num, dec) { var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec); return result; } document.getElementById("toVal").value = val * metrics[document.getElementById("fromSystem").value]/ metrics[document.getElementById("toSystem").value]; } var interval = null; function watchChanges(){ interval == null ? setInterval("convert()", 500) : clearInterval(interval); } // ]]></script> </p> <table> <tbody> <tr> <td><input id="fromVal" style="width: 100px;" onfocus="watchChanges()" onblur="watchChanges()" type="text" /><select id="fromSystem" onchange="convert()"> <option value="mm">millimeters</option> <option selected="selected" value="cm">centimeters</option> <option value="m">meters</option> <option value="foot">feet</option> <option value="inch">inches</option> </select></td> </tr> <tr> <td colspan="1" align="center">=</td> </tr> <tr> <td><input id="toVal" style="width: 100px;" type="text" disabled="disabled" /><select id="toSystem" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option value="m">meters</option> <option selected="selected" value="foot">feet</option> <option value="inch">inches</option> </select></td> Code: <html> <head> <title>TESTING</title> <script type="text/javascript"> <!-- document.write("<input type='submit' value='submit' onclick='func()'>"); function func() { document.write("<input type='submit' value='New Button' onclick='func()'>"); window.alert("THIS"); } --> </script> </head> <body> <!--input type="button" value="Read" onclick="ReadFiles()"--> </body> </html> This is a very basic version of what I am trying to do. I have a dynamic list which is set in a table. When clicked, a function is run to set up a new list.. The reason I explain that, is that I need to keep it dynamic. Now for the problem: When I run this page, I have the button made right away, then when clicked it creates the new button. The new button should also run the function to create the new button again, but when I click it, I only receive "error on page". I don't know if there is a better way to go about this, but as for this route, I am stuck. Any help is greatly appreciated! -Shane 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. 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 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> Hi, I am hoping I just need to be pointed in the right direction with this. I have Page1. When Page1 body onloads it uses Ajax to call PartA Within PartA I have a message board so members can write messages which will be sent to my database in PartA[1] and immediately posted for view on to PartA[2]. As I want to have my request to the server updating regularly I want to have PartA[2] on a timed loop to refresh - I do not need the content of PartA[1] to refresh. So the order of events would look like this: Page1 | onload call | v PartA / \ V V PartA[1] PartA[2] (loads once) (constantly refreshes) What I am not sure about is that I have <body> and <head> attributes in Page1 only. I have already used my body onload to call PartA (and can't use it to call PartA[2] before PartA has loaded anyway). I do not want the user to have to click a button or do anything to call up PartA[2]. So my question is how would I get PartA[2] to automatically load within PartA? I hope I have made this clear, but if I haven't let me know and I will try again. I'm trying to implement this 'ajax' script, however i'm getting the following error: function expected line 25. And I'm not the only person who is getting this error message :S How can the code be altered so it will work? Also the script isn't executed when I change onclick in onload :S How come and how can I change it so that it will be executed on launch? http://chriscook.me/web-development/...icking-a-link/ My problem is that I am trying to call an function within an SWF. Now, I already know how to setup my SWF and that isn't the problem. The problem is that when I try to call the function using Javascript, I am told that the function doesn't exist. I'll show you the code right here. Code: function AudioPlayerEmbed( e ) { if ( e.success ) { e.ref.LoadAudio( 'http://therevolve.com/upload/userfiles/Music/Alec_Smith1.mp3' ); } } swfobject.embedSWF("player/MP3Player.swf", "flash", "300", "90", "9.0.0", "player/expressInstall.swf", null, null, null, AudioPlayerEmbed ); HOWEVER, when I put some alert before the call, it happens to work. What is going on? Code: function AudioPlayerEmbed( e ) { alert("A"); if ( e.success ) { e.ref.LoadAudio( 'http://therevolve.com/upload/userfiles/Music/Alec_Smith1.mp3' ); } } swfobject.embedSWF("player/MP3Player.swf", "flash", "300", "90", "9.0.0", "player/expressInstall.swf", null, null, null, AudioPlayerEmbed ); Here is a live example. Any help would be appreciated. If you need more information, I can provide it. Hello, if in a webpage is included a javascript file (for example code.js) can I from my browser call a function contained in code.js and will it works correctly? I'm not meaning that the function is called in the page with or without a link to click, but it is only in code.js! Thank you! Hello. Started my massive JavaScript career just yesterday and the forums I frequent still lack a proper BB-code hide-tag, so I figured I'd try make it in JavaScript, since HTML is allowed on there. This is what I did: Code: <script type="text/javascript"> function show() { document.getElementById('silHideTextTag').innerHTML='Hidden text!!'; document.getElementById('silHideTextBtn').value='Hide'; document.getElementById('silHideTextBtn').onclick='hide()'; } function hide() { document.getElementById('silHideTextTag').innerHTML=' '; document.getElementById('silHideTextBtn').value='Show'; document.getElementById('silHideTextBtn').onclick='show()'; } </script> <input type='button' id='silHideTextBtn' onclick='show()' value='Show'/> <div id='silHideTextTag'> </div> The button labelled "Show" appears fine, when I click it it becomes "Hide" and the text "Hidden text!!" is shown. However, when I click the button again, nothing happens at all. I don't quite understand where the problem is. Thanks in advance for any clues. Best regards, Zyl 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 make an onblur that calls a function and passes it some text, for example: onblur = "function("Hello")" however this wont work as it is not even calling the function. I have tried all the different encapsulation tags I can think of but still no luck is there any way of doing it or can I assign the text to a variable and call the function in the onblur? Thanks.:confused: <frameset rows="30%,70%> <frame src="page1.html" name="name1" frameborder="0"></frame> <frame src="page2.html" name="name2" frameborder="0"></frame> </frameset> in above code I used page1.html & page2.html as frame. Both include same javascript file having two function name fun1() & fun2(). as both are separate frame both have there own copy function page1.html fun1() fun2() page2.html fun1() fun2() I call fun2() from page2.html and inside that function I want to call page1.html's fun1(). fun1() in page1.html and fun1() in page2.html both return different result because of there global variables. Is there any way to call fun1()-page1.html from the fun2()-page2.html? |