JavaScript - Why Is This Code Not Working? (basic Example)
Code:
<html> <head> <title>Click the button</title> <script type="text/javascript"> function x() { window.alert('1'); window.alert('2'); window.alert('3'); } document.getElementById("y").onclick = x; </script> </head> <body> <form> <input type="button" value="Click the button" id="y" /> </form> </body> </html> By the way... Are there any good websites / validators that can be helpful in situations like that? I've been looking at this one so far: http://www.jslint.com/ Thanks. Similar TutorialsHello, Im new to scripting. I have 2 scripts that work in firefox but not in ie. I was wondering if anyone could help me? The First Javascript Code: <SCRIPT language="javascript"> <!-- // ***** GET TOTAL function CalculateSum(setup, month, plan, form) { var A = parseFloat(setup); var B = parseFloat(month); form.x_amount.value = A + B; form.user5.value = plan; } --> </SCRIPT> The second javascript Code: var os_price = 0; var base_price = 0000; var total_carryover = 0000; function show_price() { features = 0; for(var pr in price) { features+=price[pr]; } month = features + base_price + os_price ; total = month + total_carryover; document.getElementById('setup_price').innerHTML="$"+(setup)/100; document.getElementById('monthly_price').innerHTML="$"+(month)/100; document.getElementById('total_price').innerHTML="$"+((total)/100+setup/100); } Thanks in advance for any help. This is very basic yet i can find the answer. How do you stop a countdown function?
Code: <html> <body> <script type="text/javascript"> var Items = new Array Items [0] = ["a", "b"]; Items [1] = ["c", "d"]; var i = 0; if(Items [i++][0] == "c"){ document.write("hello"); } </script> </script> <body> </body> </html> so im trying to search an array with this function its not working i tried using firebug but it showed no errors. I think its the i++ part i want to increment i each time it tries it. WAIT SORRY I SOLVED IT I solved it you can put in Pistol or shotgun for name Code: <html> <body> <script type="text/javascript"> var Items = new Array Items [0] = ["Pistol", "50", "2000"]; Items [1] = ["shotgun", "5000","1000"]; var i = 0; function chek(){ if(Items [i][0] == document.getElementById("name").value){ document.getElementById("a").value = Items [i] [1]; document.getElementById("acc").value = Items [i] [2]; i=0; } else { i++ } } </script> </script> <body> Dammage<input type="text" id="a" /> <br/> ACC<input type="text" id="acc" /> <br/> Name<input type="text" id="name" /> <br/> <input type="button" onclick="chek();" value="Chek" /> </body> </html> Is there anyway to make it more streamline so you dont have to click to increment? Working on college assignment, cant figure it out and need help! Basically a form that asks the user to fill in a valid email and password (ill give them the password), doesnt matter if it isnt secure, or if the email accepts dodgy emails (im just verifying the @ and a . and that is ok for the purpose of this. Anyway been trying with this code for ages now and cant see what is wrong but it isnt working, ive swapped it around and at times it does check that it is a valid email, sometimes it allows empty inputs. here is the code <script type="text/javascript"> function validateForm() { var x=document.forms["myForm"]["email"].value var y=document.forms["myForm"]["password"].value var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Not a valid e-mail address"); return false; } </script> I think i need something like && (y!="123") around the 'if' statement, but not a clue how or where it goes. Basically im going to set the password to 123 so dont have to allow for caps etc. Easiest way to do this, anyone plleeeeeaaasseee?? Kind regards Alan Hey everyone here is my code for looking up a city, and state by zip code. I am getting no errors and i believe it should work, but the code does not seem to want to function. Any ideas? Here is my code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>City and State Lookup</title> <style type="text/css"> h1 { font-family:Arial; color:navy; } p, td { font-family:arial; font-size:11px; } </style> <script type="text/javascript"> /* <![CDATA[ */ var httpRequest = false; function getRequestObject() { try { httpRequest = new XMLHttpRequest(); } catch (requestError) { try { httpRequest = new ActiveXObject ("Msxm12.XMLHTTP"); } catch (requestError) { try { httpRequest = new ActiveXObject ("Microsoft.XMLHTTP"); } catch (requestError) { window.alert("Your browser does not support AJAX!"); return false; } } } return httpRequest; } function updateCityState() { if (!httpRequest) httpRequest = getRequestObject(); httpRequest.abort(); httpRequest.open("get","zip.xml"); httpRequest.send(null); httpRequest.onreadystatechange=getZipInfo; } function getZipInfo() { if (httpRequest.readyState==4 && httpRequest.status == 200) { var zips = httpRequest.responseXML; var locations = zips.getElementsByTagName("Row"); var notFound = true; for (var i=0; i<locations.length; ++i) { if (document.forms[0].zip.value == zips.getElementsByTagName( "ZIP_Code")[i].childNodes[o].nodeValue) { document.forms[0].city.value = zips.getElementsByTagname( "City") [i].childNodes[0].nodeValue; document.forms[0].state.value = zips.getElementByTagName( "State_Abbreviation")[i].childNodes[0].nodeValue; notFound = flase; break; } } if (notFound) { window.alert("Invalid ZIP code!"); document.forms[0].city.value = ""; document.forms[0].state.value = ""; } } } /* ]]> */ </script> </head> <body> <h1>City and State Lookup </h1> <form action=""> <p>Zip code <input type="text" size="5" name="zip" id="zip" onblur="updateCityState()" /></p> <p>City <input type="text" name="city" /> State <input type="text" size="2" name="state" /></p> </form> </body> </html> I wrote a script that should loop through the list of countries, and if the entry's width exceeds 70px, it should cut the extra letters and insert "..." at the end of the entry; My codes produces unexpected results. The script only modifies the entry"United States", by replacing it with "Cook Isla...". I suspect I don't use the while loop properly. Plus the script does not work at all in IE. Could someone have a look and give me a hint what went wrong. Thank you very much!!! Code: <html> <head> <title> Ellipse Practice </title> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <style type="text/css"> ul { width: 200px; margin-left: 100px; } span { white-space: nowrap; } </style> <script type="text/javascript"> function trancateAll() { var list=document.getElementsByTagName("li"); count=0; while (count<list.length) { var text=String(list[count].innerHTML); list[count].innerHTML='<span id="mySpan">'+text+'</span>'; mySpan=document.getElementById("mySpan"); mySpan.innerHTML=''; var charac=1; while( (mySpan.offsetWidth<70) && (charac<text.length)) { mySpan.innerHTML=text.substr(0,charac)+"..."; charac++; } count++; } } </script> </head> <body > <ul> <li> United States</li> <li> Australia</li> <li> New Zealand</li> <li> Democratic Republic of Congo</li> <li> Russian Federation</li> <li> Cook Islands</li> </ul> <input type="button" value="Truncate" onclick="trancateAll()"/> </body> </html> Hey guys, I am not sure why this JavaScript is not working. Can you check it out please? Thanks. --Start-- <html> <head> <title>Guess it up! </title> </head> <body> <center> <b><font size="5" ><u><b>Guess it up!<br></b></u> <br > <font size="3" > This is out of five! <br > Type in your guess: <p> </p> </font> <input name="HisGuess" type="text" size=1 value=1> <p> <input name="StartButton" type="button" value="Guess" onclick="StartGame()"> </p> <p> <script> var TheRightNumber = Math.round(Math.random * 5); function StartGame() { if (TheRightGuess == HisGuess){ alert("You got it! Nice!") else{ alert("Guess again!") } } </script> --END-- Can anyone tell my why this is not working? All answers are appreciated. Hey all, I have a javascript object which I have created and it works fine until I remove the second message box from the program steps. The alert box was only ever meant to be there for error debugging to steop me through the code. Any ideas? Code: function hyper() { this.test = ""; this.load = function(lib, ver) { alert("Starting API Library Load"); var oHead = document.getElementsByTagName('HEAD').item(0); var oScript= document.createElement("script"); oScript.type = "text/javascript"; oScript.src=lib + "/" + ver + "/api.js"; oHead.appendChild( oScript); alert("Finished Loading Library"); switch(lib) { case "test": this.test = new test(); break; case "ads": this.ads = new HAds(); break; case "chat": this.chat = new HChat(); break; case "survey": this.survey = new HSurvey(); break; default: alert("No Library"); }; } } This code works in all browsers, Safari, Chrome, Firefox, but not IE 8 in which I'm testing right now for version. The code is below: Code: <script type="text/javascript"> $(document).ready(function() { $('#form_{picture_id}').ajaxForm(function() { $(function() { setTimeout(function() { $("#picture_description").show('blind', {}, 800) }, 1000); setTimeout(function() { $("#picture_description").hide('blind', {}, 800) }, 11000); }); }); }); </script> What am I doing wrong. The code simply calls the form, then shows a DIV via BLIND then hides it using the same effect. The picture_id in {} is simply smarty PHP. Any help is much much appreciated! Simple random pic script that I found on the some other forum (I forget what it was) [CODE]var aryimages = new Array('images/pic/01.jpg', 'images/pic/37.jpg', 'images/pic/02.jpg', 'images/pic/family/08.jpg','images/pic/08.jpg', 'images/pic/food/03.jpg'); randompic.src = aryimages[Math.floor(Math.random() * aryimages.length)]; [CODE] code anchors to HTML markup [CODE]<img name="randompic" id="bg" />[CODE] it is working perfectly for Safari and Chrome. Nothing is showing for FF. Any suggestions appreciated. Code: function addEvent(elem,type,func) { var obj = document.getElementById(elem); if(window.addEventListener) { obj.addEventListener(type,func,false); } if(window.attachEvent) { obj.attachEvent('on'+type,func); } } function $e(obj) { if(obj) obj = document.getElementById(obj); if(!obj) return; return obj; } function homeFunc() { $e('home-wrapper').innerHTML = "<div id=\"choose-container\"><span class=\"choose-buttons\" onclick=\"loginFunc()\">Login Exisiting Account</span><span class=\"choose-buttons\" id=\"createAcct\">Create An New Account</span><span class=\"choose-buttons-highscores\" id=\"createAcct\">Highscores Table</span>"; } function loginFunc() { $e('home-wrapper').innerHTML = "<div id=\"login-container\"><div id=\"error-field\"></div><form method=\"post\" onsubmit=\"return validate_login()\" action=\"./index.php\"><label for=\"username\">Username</label><input name=\"username\" id=\"username\" class=\"input\" type=\"text\" /> <label for=\"password\">Password</label><input name=\"password\" id=\"password\" class=\"input\" type=\"password\" /><input name=\"login\" type=\"submit\" value=\"Login\" class=\"loginButtonClass\" /><div id=\"loginQuickLinks\"><span class=\"loginQuickLinks\" onclick=\"homeFunc()\">Register</span> - <span class=\"loginQuickLinks\">Forgot password?</span></form></div></div>"; } function createAcct() { alert("Create An Account"); } function validate_usr() { var usr = $e('username'); var pwd = $e('password'); if(usr.value.length <= 0 && pwd.value.length <= 0) { loginErrorMsg('Please supply a username and password.'); return false; } if(usr.value.length >= 1 && pwd.value.length <= 0) { loginErrorMsg('Please supply a password.'); return false; } if(pwd.value.length >= 5 && usr.value.length <= 0) { loginErrorMsg('Please supply a username.'); return false; } if(pwd.value.length < 5) { loginErrorMsg('Invalid username or password.'); return false; } if(usr.value.length >= 1 && pwd.value.length >= 5) { $e('error-field').style.cssText='display:block;'; $e('error-field').innerHTML = "<img src=\"/images/ajax-loader.gif\" /> <span style=\"color:#ffffff\">Loading...</span>"; var req; var params = 'user='+encodeURIComponent(usr.value.toLowerCase())+'&pass='+encodeURIComponent(pwd.value.toLowerCase()); if(window.XMLHttpRequest) { req = new XMLHttpRequest(); } if(window.ActiveXObject) { req = new ActiveXObject("Msxml2.XMLHTTP" || "Microsoft.XMLHTTP"); } req.open('POST','server/userChck.php',true); req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); req.send(params); req.onreadystatechange = req; if(req.readyState == 4 && req.status == 200) { if(req.responseText == 0) { window.scrollTo(0,1); setTimeout(function(){loginErrorMsg('Invalid username or password');},1000); return false; } } } return true; } function loginErrorMsg(msg) { window.scrollTo(0,1); $e('error-field').innerHTML = msg; $e('error-field').style.cssText='display:block'; } function validate_login() { var isTurn = (!validate_usr()) ? false : true; return isTurn; } window.onload = function() { setTimeout(function(){window.scrollTo(0,1);},100); addEvent('loginButton','click',loginFunc); addEvent('createAcct','click',homeFunc); } This code works fine when I set this line to false Code: req.open('POST','server/userChck.php',false); but as soon as I set this to true. I doesn't work.... What am I doing wrong here? This code is not working correctly when you type get_data it should only work if you already have typed load_hacker. But get_data works withought load_hacker.
Code: <script type="text/javascript"> function command(){ if(command.value = "load_hacker" && level.value == 1){ document.getElementById("command").value = ""; document.getElementById("number").value = ""; plus(); } else { document.getElementById("command").value = "..."; document.getElementById("number").value = "..."; } if(command.value = "get_data" && level.value == 2){ document.getElementById("command").value = ""; document.getElementById("number").value = ""; plus(); } else { document.getElementById("number").value = "..."; document.getElementById("command").value = "..."; } } </script> <script type="text/javascript"> function plus(){ document.getElementById("level").value ++; } </script> ><input type="text" value="" id="command" size="" style="background-color:transparent;border:0px solid white;" /> #<input type="text" value="" id="number" size="10" style="background-color:transparent;border:0px solid white;" /> <input type="button" value="Enter" onclick="command()" /> <input type="hidden" value= 1 id="level" /> Can't get this to work...could someone read thru this and see if anything is missing? Thanks Code: <html> <head> Supporting files: lhouse.css, list.js, logo.jpg <title>The Lighthouse</title> <link href="lhouse.css" rel="stylesheet" type="text/css" /> <script src="list.js" type="text/javascript"></script> <script type="text/javascript"> function amountTotal() { total(0); for (var i=0; i<=amount.length; i++) { total+=amount[i]; } return total; } </script> </head> <body> <div id=title> <img src=logo.jpg alt=The Lighthouse /> The Lighthouse<br /> 543 Oak Street<br /> Delphi, KY 89011<br/> (542) 555-7511 </div> <div id=data_list> <script type="text/javascript"> document.write("<table border=1' rules=rows cellspacing=0'>"); document.write("<tr><th>Date</th><th>Amount</th><th>First Name</th><th>Last Name</th><th>Address</th></tr>"); for (i=0; i< amount.length; i++) { if (i%2==0) document.write("<tr>"); else document.write("<tr class='yellowrow'>"); document.write("<td>"+date[i]+"</td>"); document.write("<td class=amt>"+amount[i]+"</td>"); document.write("<td>"+firstName[i]+"</td>"); document.write("<td>"+lastName[i]+"</td>"); document.write("<td>"); document.write("<td>"+street[i]+"<br/>"); document.write("city[i],+" +state[i]+ "+zip[i]"); document.write("</td>"); document.write("</tr>"); } document.write("</table>"); </script> </div> <div id=totals> <script type="text/javascript"> document.write("<table border=1' cellspacing=1'>"); document.write("<tr><th id=sumTitle colspan=2'>Summary</th></tr>"); document.write("<tr><th>Contributors</th>"); document.write("<td>+amount.length+</td></tr>"); document.write("<tr><th>Amount</th>"); document.write("<td>$+amountTotal()+</td></tr>"); document.write("</table>");</script> </div> </body> </html> </html> Hi all, I've found a small script that displays the current time. The only problem is that it only works with IE and I'd like to make it work on all browsers (or at least Mozilla) Would you mind helping me ? Note: I'd like to keep the code using the "span" tag Here's the html code (to show the way I call the script): Code: <html> <head> <SCRIPT language="JavaScript" SRC="clock.js"></SCRIPT> </head> <body onLoad="clock()" bgcolor="#ECEDF3"> <font face="Verdana" size="1" color="#88A6C0"><span id="pendule" ></span> </body> </html> and here's the script I use (It's an external script that I called clock.js): I believe the declarations are OK and the problem comes from "document." I know there are differences the way IE and other browsers manage scripts but I'm not enough experienced to find all variants. Code: <!-- Begin function clock() { if (!document.layers && !document.all) return; var digital = new Date(); var hours = digital.getHours(); var minutes = digital.getMinutes(); var seconds = digital.getSeconds(); var amOrPm = "AM"; if (hours > 11) amOrPm = "PM"; if (hours > 12 ) hours = hours - 12; if (hours == 0) hours = "00"; if (minutes <= 9) minutes = "0" + minutes; if (seconds <= 9) seconds = "0" + seconds; dispTime = hours + ":" + minutes + ":" + seconds + " " + amOrPm; if (document.layers) { document.layers.pendule.document.write(dispTime); document.layers.pendule.document.close(); } else if (document.all) pendule.innerHTML = dispTime; setTimeout("clock()", 1000); } // End --> Any idea about what's wrong ? Thank you for your help Gino Hi, Please help code not working.i want the alert message to pop up when a cmbprop is selected. <script type="text/javascript"> function PropertyOwn(property) { prop=document.frmone.cmbprop.value switch(property) { case"0": // no error occured break case"1": alert("I am a rich men") break case"2": alert("i am a poor men") break case"3": alert("Thank God for this opportunity") break default: alert("Just try again") } } </script> <form name="frmone"> <select name="cmbprop" onchange="propertyOwn(this.value)"> <option value=0>--choose from one--</option> <option value=1>I have BMW</option> <option value=2>I rent a sigle room</option> <option value=3>Seing possibilities</option> </select> </form> Thanks. Clement Osei Any idea why this doesn't work? I'm trying to hide the li with ID of facebook1 if the innerHTML is one of two things. But if both return false and there is more code in there (e.g. a full url), I want to show the li with ID of facebook1 and also add the text 'Facebook Profile' to the span with ID of fbook-add. Code: <ul> <li id="facebook1"><a href="http://facebook.com"><span id="fbook-add"></span></a></li> </ul> <script type="text/javascript"> if(document.getElementById('facebook1').innerHTML.toLowerCase()=='<a href="http://"><span id="fbook-add"></span></a>') { document.getElementById('facebook1').style.display='none'; } else if(document.getElementById('facebook1').innerHTML.toLowerCase()=='<a href=""><span id="fbook-add"></span></a>') { document.getElementById('facebook1').style.display='none'; } else { document.getElementById('fbook-add').innerHTML=='Facebook Profile'; } </script> I havent even declared x,y and z as variables! Code: x=10; y=20; z = x+y; document.getElementById('good').innerHTML=z; I am getting so confused... since the time i started learning JS i thought declaring variables (var x,y,z was real important! I am trying to insert a new paragraph with javascript, however my code is not working, even though i pretty much copied my code from the book. Could someone please tell me why i have a problem with a script below? Thank you very much. <script type="text/javascript"> function newtext() { var myPara=document.createElement("p"); var text="We sincerely hope that you are enjoying learning Javascript"; var paratext=document.createTextNode(text); myPara.appendChild(paratext); } </script> <p> <a href="#" onclick="newtext()"; return: true;> Insert new text </a> </p> This is suppose to execute "avalon" and it should move down the page once and "Books" should move with it, hidden behind it. I have read the code over and over and over and do not see any mistakes. HELP! Code: <title>Avalon Books</title> <link href="styles.css" rel="stylesheet" type="text/css" /> <script src="scripts.js" type="text/javascript"></script> <script type="text/javascript"> function placeObjects() { placeIt("avalon",175,10); placeIt("books", 175,10); placeIt("ab",230,40); placeIt("fiction",5,5); placeIt("nfiction",475,5); hideIt("ab"); hideIt("fiction"); hideIt("nfiction"); moveAvalon(); } function moveAvalon() { var y=yCoord("avalon"); if (y <= 260) { shiftIt("avalon",0,10); shiftIt("books",0,10); setTimeout("moveAvalon()",30); } else { moveBooks(); } } function moveBooks() { var x=xCoord("books"); if (x <= 320) { shiftIt("books",10,0); setTimeout("moveBooks()",50); } else { //display the hidden images; } } </script> </head> <body onload="placeObjects()"> <div id="avalon"> AVALON </div> <div id="books"> BOOKS </div> <div id="ab"> <a href="#"> <img src="ab.jpg" alt="Click to enter store" /> </a> </div> <div id="fiction"> <img src="fiction.jpg" alt="" /><br /> <b>AB Sales Rank: #1<br /> Fiction</b><br /> <i>Before the Fall</i><br />Jeffrey Unwin </div> <div id="nfiction"> <img src="nfiction.jpg" alt="" /><br /> <b>AB Sales Rank: #1<br /> Nonfiction</b><br /> <i>Vietnam Memoirs</i><br />Gen. John Hartford </div> </body> </html> This code originally worked, but now it doesn't. It's suppose to count the number of characters you type. The form processes fine, but it's not counting, it always says 1,000 in the box. Any ideas? Thanks Code: <script type = "text/javascript"> var maxLen = 1000; // max number of characters allowed // global variable var max = "You may enter up to " + maxLen + " characters"; // global variable function OnPaste () { //return false; // cancels (blocks) the onpaste event. Uncomment this line to block pasting setTimeout(checkMaxInput,100); // delay is necessary } function initCount() { document.getElementById("limit").innerHTML = max; document.getElementById("remLen").value = maxLen; } function checkMaxInput() { var form = document.myform; // or document.forms[0] or document.getElementById("myform"); if (form.txtarea.value.length > maxLen) { // if too long.... trim it! form.txtarea.value = form.txtarea.value.substring(0, maxLen); document.getElementById("message").innerHTML = "Too many characters were entered!! The excess over " + maxLen + " have been removed."; } else { document.getElementById("message").innerHTML = ""; } form.remLen.value = maxLen - form.txtarea.value.length; } </script> <body onload = "initCount()"> <form name = "myform" id = "myform"> <span id = "limit" style="font-size: 10pt;color: #FF0000;font-family: arial, helvetica, sans-serif;"></span> <br> <textarea name="txtarea" wrap=physical cols=48 rows=10 onkeyup="checkMaxInput()" onblur="checkMaxInput()" onpaste="OnPaste ()" > </textarea> <br> <input readonly type=text name=remLen id = "remLen" size=3 value = ""> characters left</font> </form> <span id = "message" style="color:red";></span> |