JavaScript - Please Help Switch Code Not Working.
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 Similar Tutorialshi, I have a few links on my website as follows: Code: <a href="javascript:switchid('a6');">Link 6</a> but when I view source it comes out like this: Code: <a href='javascript:switchid('>Link 6</a> Can someone please help? Hi everyone, I'm a beginner who has now come across the switch statement and has been trying to understand it with this simple coding i came up with. I think I have the syntex of the switch command correct but I'm trying to get it to work along with a HTML form and a function. I've been trying to figure out what i am do wrng but can not seem to see the solution. can someone guide me to the solution? thanks John Code: <html> <head> <title>Using the switch statement.</title> <script type="text/javascript"> function basegraincheck(){ var basegrain = document.basegrainform.basegrain1.value return basegrain } switch (basegrain) { case 1 : displaygrain = "US Pale ale malt" break case 2 : displaygrain = "Maris Otter Malt" break case 3 : displaygrain = "Crystal Malt" break default: displaygrain = "somethings wrong with the switch statement" } document.write(displaygrain); </script> </head> <body> <form name="basegrainform" action="" method="get" onsubmit="basegraincheck()"> <h2>Select a grain</h2> <br> <p>Pale ale Malt</p> <input type="radio" name="basegrain1" value="1"> <br> <p>Maris Otter Malt</p> <input type="radio" name="basegrain1" value="2"> <br> <p>Crystal Malt</p> <input type="radio" name="basegrain1" value="3"> <br> <input type="submit" value="Submit"> </form> </body> </html> Since the upgrade from chrome 9 to chrome 10 my script is showing an error in my variables when i use boolean expressions. they changed to version V8, Chrome's JavaScript engine. Here is the function function get_form_value(n){ e=document.getElementById(n); if ((e.value)&&(e.value != "")&&(!e.options)) return e.value; if ((e.selectedIndex)&&(e.selectedIndex>0) &&(e.options[e.selectedIndex].value !="")) return e.options[e.selectedIndex].value; // select if ((e.text)&&(e.text.value !="")) continue; if ((e.selectedIndex)&&(e.selectedIndex>0) &&(e.options[e.selectedIndex].text !="")) return e.options[e.selectedIndex].text; // select if ((e.checkbox)&&(e.checkbox.checked)) return true; return false; } When i run it it shows a syntax error: Can someone please help me fix this? 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 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"); }; } } 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. index.html Code: <html> <head> <title>:: wtmp</title> </head> <body> <p>Welcome to my page</p> <script type="text/javascript" src="file.js"></script> </body> </html> file.js Code: function one(p1, p2) { var j_text=p1+" "+p2; return j_text; } function two() { var rslt=one("Hi", "there!"); } document.write(rslt); var mainscrpt=one("Hello", "world!"); window.alert(mainscrpt); 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> 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? 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. I changed the code and it didn't work, so I tried to put it back to what it was. Now, the whole thing isn't working. I am a lost little child. Can someone help me please. http://www.boothemusic.com/ Here is the code: Code: <html xmlns="http://www.w3.org/1999/xhtml"> <head xmlns=""> <title>Boothe Brothers Music</title> <script type="text/javascript"> function loadContent(page) { switch(page) { case "home": document.getElementById("middle").src = "http://boothemusic.com/middle.html"; break; case "store": document.getElementById("middle").src = "http://boothemusic.com/catalog"; break; case "Electric Guitars": document.getElementById("middle").src = "http://boothemusic.com/catalog/index.php?main_page=index&cPath=1&zenid=9feb6660698a06a51571cc4cef1c3e60"; I left out most of the code because I only edited the line "case "store".....". 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 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> 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> 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> 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! 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. 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 |