JavaScript - Buttons Declaring That Functions Are Not Defined, Also Else Statement Issues.
Hey guys, i'm taking on my first minor project in javascript and i've run into an error. For whatever reason, buttons i've defined are calling on functions that supposedly don't exist, yet they are clearly in the code and can be applied anywhere. I also checked the syntax errors in google chrome and they state:
Uncaught SyntaxError: Unexpected token else Uncaught reference error: go() is not defined Uncaught reference error: highscore() is not defined. So without further delay, here is the full code. Can anyone help me out? Code: <html> <head> <script type="text/JavaScript"> <!-- var sam = 9; var sally = 8; var donald = 4; function percentage (score) { return score / 10 * 100; }; function go() { document.write("Sam's score on the test is " + percentage(sam) + "%, <br \> Sally's score on the test is " + percentage(sally) + "%, <br \> Donald's score on the test is " + percentage(donald) + "%"); }; function highscore() { if (Math.max(90, 80, 40) === 90){ document.write("Sam's score was the highest.")}; else if (Math.max(90, 80, 40) === 80){ document.write("Sally's score was the highest.")}; else{ document.write("Donald's score was the highest.")} }; //--> </script> </head> <body> <input type="button" onclick="go()" value="Student Grades"> <br \> <input type="button" onclick="highscore()" value="Highest Score"> </body> </html> Similar TutorialsHello again, CodingForums. I have a .php page that generates the following javascript which is intended to hide/show a form somewhere on the page. (It only shows right now because it's not done yet.) However, after the page is rendered and given to the client, the function calls do not work, and the error console reports that "[function name] is not defined." Code: <script type="text/javascript"> function showEdit(num) { var elem = document.getElementById("form-wrap"+num); var str = "<form action=\"./blog.php\" method=\"POST\" class=\"blogform\">"; str = str + "<input type=\"hidden\" name=\"u\" value=\"Webmaster\"/>"; str = str + "<input type=\"hidden\" name=\"q\" value=\"edit\"/>"; str = str + "<input type=\"hidden\" name=\"n\" value=\""+num+"\"/> str = str + "<label for=\"title\">Title</label>"; str = str + "<input type=\"text\" name=\"title\" value=\""+document.getElementById("title"+num).innerHTML+"\"/>"; str = str + "<label for=\"picture\">Picture</label>"; str = str + "<input type=\"file\" name=\"picture\"/>"; str = str + "<label for=\"caption\">Picture Caption</label>"; str = str + "<input type=\"text\" name=\"caption\" value=\""+document.getElementById("post-image"+num).getAttribute("title")+"\"/>"; str = str + "<label for=\"content\">Entry Text</label>"; str = str + "<textarea name=\"content\" cols=\"100\" rows=\"20\" class=\"blogtextarea\">"+document.getElementById("content"+num).innerHTML+"</textarea>"; str = str + "<input type=\"submit\" value=\"Edit Post\"/>"; str = str + "</form>"; elem.innerHTML = str; } function showDelete(num) { var elem = document.getElementById("form-wrap"+num); var str = "<form action=\"./blog.php\" method=\"POST\" class=\"blogform\">"; str = str + "<input type=\"hidden\" name=\"u\" value=\"Webmaster\"/>"; str = str + "<input type=\"hidden\" name=\"q\" value=\"delete\"/>"; str = str + "<input type=\"hidden\" name=\"n\" value=\""+num+"\"/> str = str + "<label for=\"really\">Delete this post?</label>"; str = str + "<input type=\"radio\" name=\"really\" value=\"Yes\">Yes</input><br/>"; str = str + "<input type=\"radio\" name=\"really\" value=\"No\" checked=\"checked\">No</input><br/>"; str = str + "<input type=\"submit\" value=\"Confirm\"/>"; str = str + "</form>"; elem.innerHTML = str; } function showNew(num) { var elem = document.getElementById("new-form-wrap"); var str = "<form action=\"./blog.php\" method=\"POST\" class=\"blogform\">"; str = str + "<input type=\"hidden\" name=\"u\" value=\"Webmaster\"/>"; str = str + "<input type=\"hidden\" name=\"q\" value=\"new\"/>"; str = str + "<input type=\"hidden\" name=\"n\" value=\""+num+"\"/>"; str = str + "<label for=\"title\">Title</label>"; str = str + "<input type=\"text\" name=\"title\"/>"; str = str + "<label for=\"picture\">Picture</label>"; str = str + "<input type=\"file\" name=\"picture\"/>"; str = str + "<label for=\"caption\">Picture Caption</label>"; str = str + "<input type=\"text\" name=\"caption\" />"; str = str + "<label for=\"content\">Entry Text</label>"; str = str + "<textarea name=\"content\" cols=\"100\" rows=\"20\" class=\"blogtextarea\"></textarea>"; str = str + "<input type=\"submit\" value=\"Create Post\"/>"; str = str + "</form>"; elem.innerHTML = str; } </script> These are all the elements that call the javascript functions. Code: <a onclick="showNew('2');" class="edit-delete">Create New Entry</a> <a onclick="showDelete('1');" class="edit-delete">Delete</a> <a onclick="showEdit('1');" class="edit-delete">Edit</a> <a onclick="showDelete('0');" class="edit-delete">Delete</a> <a onclick="showEdit('0');" class="edit-delete">Edit</a> I have no idea why my functions aren't being recognized by the interpreter as such, but it's probably something simple. Thanks in advance for the help, and I'll be happy to post more code if it might be relevant. Hello, Ok so the following code works. Code: function myFunction(myName) { alert("You are "+myName); } callFunction = "myFunction"; parameter = "Joe"; window[callFunction](parameter); However this code doesn't work: Code: function myFunction(myName, myAge) { alert("You are "+myName+" and "+myAge+" years old."); } callFunction = "myFunction"; parameter = "Bill,15"; parameter = parameter.split(","); window[callFunction](parameter); The above code alerts: "You are Bill,15 and undefined years old." Thanks for the help! hi im new to javascript and after hours of trying to figure it out myself and failing, i might as well just ask for help the problem is really simple... http://i307.photobucket.com/albums/n...eaker/help.jpg check the image^ what i want to do is after selecting an item from the drop down menu and clicking "Go" an image underneath the button will show up ex.(i pick a and click on Go and an image of an airplane shows up, i pick b and click Go and an image of a boat shows up, etc) help please? Hello, I have a form with two yes/no questions that have radio buttons for the yes or no answer. Each question has a yes and a no button. If the user answers yes to the first question then they must answer the second question. If they answer no to the first question then they don't have to answer the second question. I have some code to pop an alert if the first question is not answered but I haven't been able to make the second part work (if answer is yes, then pop an alert if the second question is not answered or forget it if it is not. The radio buttons for the first question each have the same name (yesNo1) but one value is yes and the other is no. The second question buttons have the name yesNo2. Here's the code for the first part: Code: function radio_button_checker() { // set var radio_choice to false var radio_choice = false; // Loop from zero to the one minus the number of radio button selections for (counter = 0; counter < frm1.yesNo1.length; counter++) { // If a radio button has been selected it will return true // (If not it will return false) if (frm1.yesNo1[counter].checked) radio_choice = true; } if (!radio_choice) { // If there were no selections display an alert box alert("Please select Yes or No to the first question of Section D.") return (false); } return (true); } I thought I could use the same code with some name changes and with an If statement to check the second question but I haven't been able to get it right at all and I spent all day messing with this stuff. I thought I should put the code for the second question check right in the spot where the return (true) is but so far no luck. I'm new to javascript so any help would be appreciated. Thanks, Rick Hi I need a bit of javascript help with an array please. just don't seem to have the correct syntax. (the "code" below is pseudo code, just to get the idea across) Here's what I currently have: var bill = new array[20]; var sam = new array[20]; var nancy = new array[20]; var Oscar = new array[20]; I'm assigning objects to them (ie Oscar[5] = new objLabel() This seems like a kluge, however. Here's what I'd like (again, pseudo-code) var Objects = {bill:null; sam:null; nancy:null; Oscar:null}; var theObject = new Array of Objects[20]; // yes: i know that's wrong... and that's the part I'm having trouble with so that I can do something like: with theObject[5] do { bill = new objLabel(); nancy = new objImage(); }; Just seems to me that keeping a single array of multiple objects is likely to be less error-prone than multiple arrays of single objects... But I don't have the syntax right... or can it be done in JS? If it's doable, would someone be kind enough to show me how to declare and access that example? Hi all, I'm a javascript newbie and having some trouble with what I imagine it s a very basic issue! I am trying to declare a variable inside a function and use it later on in my code... but it just already returns white space... i.e. not variable value. I am setting it within this function: Code: function show_video1(){ document.getElementById('video1').style.display="block"; var video1Name = "Education World News (Part 1)"; document.getElementById('video2').style.display="none"; document.getElementById('video3').style.display="none"; document.getElementById('video4').style.display="none"; document.getElementById('video5').style.display="none"; document.getElementById('video6').style.display="none"; document.getElementById('video7').style.display="none"; document.getElementById('video8').style.display="none"; document.getElementById('video9').style.display="none"; document.getElementById('video10').style.display="none"; document.getElementById('video11').style.display="none"; } and trying to call it later on with this: Code: <script type="text/javascript">document.write(video1Name)</script> It might be worth noting that each one of my 11 videos will hace a different name. Can anyone help out a newbie? Many thanks, greens85 Hi all, Rookie (extremely) programmer here, so be gentle Trying to build a little tool here.. Code: <html> <body> Artist ID: <input type=TEXT id=ArtistID name= ArtistID value="Artist ID"> <SELECT> <OPTION value="http://URL.com/EditUser/"ArtistID.value".html">Edit User</OPTION> <OPTION value="http://URL.com/EditArtist/"ArtistID.value".html">Edit Artist</OPTION> <OPTION value="http://URL.com/Subscruptions/"ArtistID.value".html">Subscriptions</OPTION> <OPTION value="http://URL.com/ControlRoom/"ArtistID.value".html">Control Room</OPTION> </SELECT> <input type="submit" value="Chyeah"> </body> </html> Yeah. Like I said. Rookie. I'm trying to save the input and pass it into the URLs that are the option values. So Artist ID being 111 would take you to url.com/<WHATEVER OPTION YOU CHOSE FROM DROP DOWN>/111 What am I doing wrong/What am I not doing? ps if this is in the wrong forum, sorry! Feel free to move it. Couldn't decide if this should go in DOM forum or not (probably bc I don't know what DOM is!) Today I have been embedding some Google Maps on my website. When I got around to putting in event handlers for markers on the map I ran into some trouble with how to declare them in the way I have the map setup. The issue is that I have an array, label, and want to indicate a single element from that array to the event handling function. But the declaration of this seems tricky. The code in question are the two lines like this one in the script below: GEvent.addListener(marker[i], 'mouseover', function() { map.addOverlay(label[i]); }); Specifically, the problem is with function() { map.addOverlay(label[i]); because I don't want label[i] to be used, but whatever value i has should be substituded in there. But since this is a function being declared and not actually executed the value for i does not get used. I've been able to get it to work by using eval() to force the actual value of i into the code, like so: eval('GEvent.addListener(marker[i], \'mouseout\', function() { map.removeOverlay(label['+i+']); });'); but am wondering if there is a better solution? Here's a section of my script showing the issue in context. You can see that i is incremented with a loop and used as the index of a few arrays. Code: for (i = 0; i < buildings.length; i++) { icon[i] = new GIcon(); icon[i].image = 'http://labs.google.com/ridefinder/images/mm_20_red.png'; icon[i].iconSize = new GSize(12, 20); icon[i].iconAnchor = new GPoint(6, 20); map.addOverlay(marker[i] = new GMarker(new GLatLng(buildings[i][1], buildings[i][2]), {icon:icon[i]})); label[i] = new ELabel(new GLatLng(buildings[i][1], buildings[i][2]), '<nobr>'+buildings[i][3]+'<\/nobr>', 'maplabel'); GEvent.addListener(marker[i], 'mouseover', function() { map.addOverlay(label[i]); }); GEvent.addListener(marker[i], 'mouseout', function() { map.removeOverlay(label[i]); }); } Hi, I am doing a Validation for Form "Text input". If the user leaves the input empty, a function is starting to run. If the field is bigger than 1 - so it doesn't get into the function. The problem is: The first time, the user left the input empty, function ran, and I got the alert - that's OK. Second time, The user added 10 in the AGE input - And again he gets the Alert - But he should not. Note: Age input value, returns from a different function (calc) to a var called: result. this is the code: Code: $(document).ready(function(){ $('#btn_send').click(function(){ //var result gets the value from another function of input "Age" value. -> return thisform.Age.value var result = calc(document.getElementById("campaignform")); if (result<1) { $("#campaignform").submit(function(event) { event.preventDefault(); alert ("prevent default"); }); } else{ return true; }; }); }); so if you try the second time to click on Submit, then you get into $('#btn_send').click(function() and eventhough you added for example 67 in the AGE (return as result) input, you get into the IF statement which is: if (result<1) I'm pretty new to developing, so I hop you will understand me. Sorry if I have mistakes. Can you advice what could be a better TITLE for this question? thanks in advance, Shai Hi, I have written a number of functions designed to return frequency data on 1000 randomly chosen numbers using different math functions for the rounding. I would like to include all of these functions within the wrapper of another function so that only one call is needed to get returns from all of the 'inner' functions. However, while each of the functions works in isolation, the moment I wrap them in another function they stop working. The following code is one of the functions 'frequencyWrapperOne' that has been wrapped in the function 'testWrapper'. A call to testWrapper does nothing. Can anyone see what I'm doing wrong? Code: function testWrapper() { function frequencyWrapperOne() { var numberArrayOne = new Array(0,0,0); for (var i = 0; i < 1000; i = i + 1) { var chosenNumber = Math.floor(Math.random() * 3); if (chosenNumber == 0) { numberArrayOne[0] = numberArrayOne[0] + 1; } if (chosenNumber == 1) { numberArrayOne[1] = numberArrayOne[1] + 1; } if (chosenNumber == 2) { numberArrayOne[2] = numberArrayOne[2] + 1; } } return window.alert(numberArrayOne.join(',')); } } testWrapper(); Thanks. Is there a way to activate a function from another function? It has to be in the script tag, it can't be in the HTML section. Can I use something similar to this following code? If not, can anyone give me some help? I have tried to do it various ways, and have looked it up a few times, but to no avail. Can I use something similar to this following code? If not, can anyone give me some help? if (condition) {activate functionname();} Any help I can get would be appreciated. Thanks a lot to anyone who can help. Ok here is what I have so far, my ending part of my Call Function I think is ok. for my main function. I think I misplaced the { and } I will show you all the codes I have for my main function this is what I have I think I did misplace something but I can not pin point where that one small things should be Code: unction showResults(race,name,party,votes) { // script element to display the results of a particular race var totalV = totalVotes(votes); document.write("<h2>" + race + "</h2>"); document.write("<table cellspacing='0'>"); document.write("<tr>"); document.write("<th>Candidate</th>"); document.write("<th class ='num'>Votes</th>"); document.write("<th class='num'>%</th>"); document.write("</tr>"); } for (var i=0; i < name.length; i++) { document.write("<tr>"); document.write("<td>" name[i] + "(" + party[i] + ")</td>"); document.write("td class='num'>" + votes[i] + "</td>"); var percent=calcPercent(votes[i], totalV) document.write("<td class='num'>(" + percent +"%)</td>"); createBar(party[i],percent) document.write("</tr>"); } document.write("</table>"); } </script> Just wondering if i misplaced any ; or { or } anywhere suggestions? Here is my call function Code: <script type="text/javascript"> showResults(race[0],name1,party1,votes1); showResults(race[1],name2,party2,votes2); showResults(race[2],name3,party3,votes3); showResults(race[3],name4,party4,votes4); showResults(race[4],name5,party5,votes5); </script> I been going over this, I can not seem to figure out what { i might be missing? Thanks Hi guys my site is not working fireug says that the function 'changevalu()' ia not defined but it is heres my site Code: <!doctype html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html" > <title> portl - beta 0.1 </title> <meta name="description" content="portl Is a file transfer system. "> <meta name="author" content="Techyonomics"> <meta name="viewport" content="width=device-width"> <meta name="keywords" content="portl,techyonomics,school,free,privet,trans,files,ui,cool" > <link rel="stylesheet" href="style.css"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="javascript/text"> function changevalu() { var valueofpress = $(this).text(); var passval = $(#password).val(); $(#password).val(passval + valueofpress); alert(passval + valueofpress); } </script> </head> <body> <header> </header> <div role="main"> <div id="keypad"> <div id="keys"> <div class="key" onmouseup="javascript:changevalu()">1</div> <div class="key">2</div> <div class="key">3</div> </br> </br> </br> <div class="key">4</div> <div class="key">5</div> <div class="key">6</div> </br> </br> </br> <div class="key">7</div> <div class="key">8</div> <div class="key">9</div> </br> </br> </br> <div class="key">C</div> <div class="key">0</div> <div class="key">E</div> </div> <form id="hiddenform" action="login.php" method="post"> <input id="password" type="text" value="" name="pass"></form> </div> </div> <footer> </footer> </body> </html> Whole thread based on my mistake.
Code: $(document).ready(function(){ var theText=["Text one","Text two","Text three", "Text four"]; // Build the array of text var arrayRows = theText.length; //Get the length of the array (Note: This starts at 1 not 0 like the array) var i=0; //Set a counter document.getElementById('textHere').innerHTML =theText[i]; //Fill in the space with the first piece of text time = setTimeout("next()", 2000); function next() { if (i == (arrayRows-1)) { i = 0; }else { i++; } $("#textHere").fadeOut("slow", function(){ document.getElementById('textHere').innerHTML =theText[i]; $("#textHere").fadeIn("slow"); }); } function prev() { if (i <= 0) { // If its below 0 go to the max i = arrayRows-1; }else { i--; } $("#textHere").fadeOut("slow", function(){ //Fade out the area document.getElementById('textHere').innerHTML =theText[i]; //Change the text to the next piece of text $("#textHere").fadeIn("slow"); // Fade in the area }); } $("#prevText").click(function(e) { e.preventDefault(); // Stop the link being a link prev(); }); $("#nextText").click(function(e) { e.preventDefault(); next(); }); }); When i click the links the functions work, however the setTimeout doesnt, can anyone help me figure this out? JavaScript: Code: function test() { alert('dsd'); } HTML: Code: <a href="#" onClick="test()">Test Link</a> JS Error: Code: Error ``ReferenceError: test is not defined'' [x-] in file ``file:///C:/Users/Martyn%20Ball/Desktop/test.php#'', line 1, character 0. Okay wtf. I am writing a greasemonkey userscript that simply just takes the underlying width of a td tag, and prints the text in white font over the table so it is viewable to everyone. I wrote the following code Code: function main() { var page = document.getElementById("container"); var td = page.getElementsByTagName("td"); for(i=0; i<td.length; i++) { if(td[i].background-color != "") { td[i].style.color = "#ffffff"; td[i].innerHTML = td[i].width; } } } however, When i installed the script.. firefox tells me that "color" is not defined. Is there another way of doing this? Just wanting the width is white font. Ok, I have an event handler for a click - ala: using prototype and here is a snippet. Code: spotL = some_length_of_an_array; $R(1,spotL).each(function(n) { $('spot_btn_' + n).style.display = 'block'; $('spot_btn_' + n).observe("click", function(){countdwn_clear();} ); }); Now, that code above fires off AFTER I call an init function that just runs thru some things... But not only that, that function "countdwn_clear()" loads before I call the code above... so its there. Now, the "element" I am trying to attach that event handler in an anchor tag in a UL element ala. Code: <ul id="buttons" style="display: none;"> <li id="spot_btn_1" class="selected"><a href="javascript://" id="btn1">1</a></li> <li id="spot_btn_2"><a href="javascript://" id="btn2">2</a></li> </ul> so, I originally thought it that I was trying to attach an event handler to an element in another that had a display of none -- so I switched it to block and I'd still get this error: countdwn_clear is not defined NOW -- if put this right below the function call, ala: Code: function countdwn_clear(){d_some_code_here} $$("#buttons li")[0].observe("click", function(){countdwn_clear();} ); $$("#buttons li")[1].observe("click", function(){countdwn_clear();} ); ^^^^ that works! why? In one case, i am calling it right below the function and I am using a different reference: $$("#buttons li")[1] in the code where I "build" it, I have: $('spot_btn_' + n).observe("click", function(){countdwn_clear();} ); ???? could it be the event is on the "li" instead of the "a" or ? I don't get it. Any ideas? Here is my function: Code: function mod_selection(val1,val2) { if( -1 != navigator.userAgent.indexOf ("MSIE") ) { var range = document.selection.createRange(); var stored_range = range.duplicate(); if(stored_range.length > 0) { stored_range.moveToElementText(textArea); stored_range.setEndPoint('EndToEnd', range); textArea.selectionStart = stored_range.text.length - range.text.length; textArea.selectionEnd = textArea.selectionStart + range.text.length; } alert('hi'); // Get the text area var textArea = $("#text_edit"); textArea.hover(function() {alert('hi');}) // Do we even have a selection? if (typeof(textArea.selectionStart) != "undefined") { // Split the text in three pieces - the selection, and what comes before and after. var begin = textArea.value.substr(0, textArea.selectionStart); var selection = textArea.value.substr(textArea.selectionStart, textArea.selectionEnd - textArea.selectionStart); var end = textArea.value.substr(textArea.selectionEnd); // Insert the tags between the three pieces of text. textArea.value = begin + val1 + selection + val2 + end; } } } Basically what it does is insert BBCode tags for whatever text you have highlighted. Here is my HTML for it: Code: <div class="two-row"> <label>Content: </label> <a href="#" onclick="mod_selection('','');return false;">B</a> <input type="button" value="I" onclick="mod_selection('','')" /> <input type="button" value="U" onclick="mod_selection('','')" /><br /> <textarea id="text_edit" name="body" rows="25" cols="51"><?php if(isset($_POST['submit']) || isset($_POST['preview'])) { echo $_POST['body']; }else { echo $news_body; } ?></textarea> </div> It says the mod_selection is not defined. I'm doing alert('hi'); for testing purposes and it won't print hi.. sooooo I feel like I need a second pair of eyes. I want it to at least recognize the function before I debug it any further. |