JavaScript - Using While Loop For Four Different Passwords
Need to write a script that will ask for password and then give an alert with either successful login or unsuccessful login. It needs to use the while loop and I need for the script to accept four different passwords. I can script it for one password but can not figure out how to get it to work for other the passwords.
Unfortunately I don't know computer programming and very little html and was allowed to sign up for a course that is too advanced for me and I can't drop it because I will lose my financial aid so with I am really struggling in this class and the assignments do not really go with the textbook and examples provided. Here is the code I have so far: <html> <body> <script type="text/javascript"> var password = new Array ("midland", "baycity", "saginaw", "delta"); var tries = 3; password = prompt("Enter password", ""); while (password != "midland" && tries > 0) { alert("Incorrect password - You have " + tries + " more tries"); password = prompt("Enter password", ""); tries--; } if (password == "midland") alert("Login Successful"); else alert ("Login Failed - Please Try Later"); </script> </body> Similar TutorialsOk, I have no idea how to really even explain what's been asked of me, but it's seems to me that this could be a bit beyond my knowledge. We're creating an alternate reality game which starts with a series of questions that people can choose from two answers. The answers will determine which path the person will travel. They'll be given a password at the end of the series of questions. There are three possible paths, which means three possible passwords given. On the same page, beneath the questions would be a text box with a "submit" button. The password they are given would be typed in there, and then they'd proceed to the proper page. This keeps from people being able to "skip" the questions portion. What they'd proceed to next is a video which is currently being made for our event, which has hidden puzzles and clues in it to find the next password. Rinse and repeat... My problem? How the heck do I make that box and submit button and password all work together when I have more than one password? Even more so, how do I make the password/submit button direct someone to the correct URL (without revealing the URL, and also prevents anyone from copying the URL and sharing it to bypass the password request)? For example: Questions are complete and the password "invention" is given. The person types in the word invention and presses submit. It directs the to www.url.com/game1 automatically. While someone else will come in, answer the questions, and the password "intelligence" would be given. That person types in the word intelligence and presses submit into the same box, using the same button that the person who typed in the word invention typed in. But this person would instead be directed to www.url.com/game2 If either person shared the link they were directed to, then it'd prompt people to put in a password before letting them in. How in the darn world do I make this happen?? LOL! Thanks in advance for any time, advice, or tutorials provided! ---------------------------------------- Added later.... I might need to go ahead and ask this as well.. since it got me to thinking.. How would I go about hiding the URL as well. I'm only interested in doing it for the game side of the site to keep from people sharing that URL and stripping the "fun" away from the game. Hopefully it is something simple? I'm fairly new at coding. My knowledge is no where as vast as I see many others here are. So if you should decide to have the patience to assist me, please be specific in steps like you are describing this to your kid who has no idea what you're talking about. I hate to present it that way, but I don't want to annoy anyone by stating I don't understand. Hi all, I'm trying to match two passwords to one another. The user enters the password into two fields and onblur from the second field, the function runs. Here is my code: Code: function validatePassword(inputField, inputField2, helpText, helpMessage) { // First see if the input value contains data if (!validateNonEmpty(inputField, helpText)) return false; var inputField = document.getElementById('inputField').firstChild.nodeValue var inputField2 = document.getElementById ('inputField2').firstChild.nodeValue } if (inputField !== inputField2) { // The data is invalid, so set the help message and return false if (helpText != null) helpText.innerHTML = helpMessage; } else { // The data is OK, so clear the help message and return true if (helpText != null) helpText.innerHTML = ""; } }; Code: document.getElementById('password2').onblur = function() { validatePassword(this, document.getElementById('password'), document.getElementById('password2_help'), "<p>Passwords don't match</p>'"); }; I am passing a help text to a span element inside the form: Code: <div class="fieldset"> <label for="password2">Confirm:</label> <input type="password" id="password2" name="password2" /> <span id="password2_help" class="help"></span><br/> </div><!--fieldset--> What's going on here? As far as I can tell it this should be working. Thanks, Andrew Pls help me as to how to code for the password form in html and then make it to be recognized in a notepad. what i mean is... when logging in or when entering a password the html should look or match it in a notepad and see if its the correct one. and to at least allow people to register and save the passwords in that same notepad. Thanks in advance Ok, I'm nearly pulling my hair out with this one. I have been looking at this code for two evenings now, and rewrote it 4 times already. It started out as jQuery code and now it's just concatenating strings together. What I'm trying to do: Build a menu/outline using unordered lists from a multidimensional array. What is happening: Inside the buildMenuHTML function, if I call buildMenuHTML, the for loop only happens once (i.e. only for 'i' having a value of '0'.) If I comment out the call to itself, it goes through the for loop all 3 times, but obviously the submenus are not created. Here is the test object: Code: test = [ { "name" : "Menu 1", "url" : "menu1.html", "submenu" : [ { "name" : "menu 1 subitem 1", "url" : "menu1subitem1.html" }, { "name" : "menu 1 subitem 2", "url" : "menu1subitem2.html" } ] }, { "name" : "Menu 2", "url" : "menu2.html", "submenu" : [ { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" }, { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" } ] }, { "name" : "Menu 3", "url" : "menu3.html", "submenu" : [ { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" }, { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" } ] } ]; Here is the recursive function: Code: function buildMenuHTML(menuData,level) { var ul; if (level == 1) { ul = "<ul id='menu'>"; } else { ul = "<ul class='level" + level + "'>"; } for (i = 0; i < menuData.length; i++) { menuItemData = menuData[i]; ul += "<li>"; ul += "<a href='" + menuItemData.url + "'>" + menuItemData.name + "</a>"; if (typeof menuItemData.submenu != 'undefined') { ul += buildMenuHTML(menuItemData.submenu,level + 1); } ul += "</li>"; } ul += "</ul>"; return ul; } Here is how the function is called initially: Code: buildMenuHTML(test,1); This is it's return value (with indentation added for readability): Code: <ul id='menu'> <li><a href='menu1.html'>Menu 1</a> <ul class='level2'> <li><a href='menu1subitem1.html'>menu 1 subitem 1</a></li> <li><a href='menu1subitem2.html'>menu 1 subitem 2</a></li> </ul> </li> </ul> 'Menu 2' and 'Menu 3' don't show up! I'm sure it's something small that I'm overlooking, but any help would be appreciated. Hi all I'm well aware that I can't post assignments here and expect an answer, however, I have been staring at this code for so long. I feel I am close to the solution (to get the correct output to the browser) but I just cannot get it to count how many moves it takes. I don't want an answer, but a nudge in the right direction would be very grateful. As you can see from the code and the output, it will attempt to write to the browser how many moves, but only '0'. Code: function rollDie() { return Math.floor(Math.random() * 6) + 1; } /* *searches for a number in a number array. * *function takes two arguments * the number to search for * the number array to search *function returns the array index at which the number was found, or -1 if not found. */ function findIndexOf(number, numberArray) { var indexWhereFound = -1; for (var position = 0; position < numberArray.length; position = position + 1) { if (numberArray[position] == number) { indexWhereFound = position; } } return indexWhereFound; } //ARRAYS that represent the board -- you do not need to change these //array of special squares var specialSquaresArray = [1,7,25,32,39,46,65,68,71,77]; //array of corresponding squares the player ascends or descends to var connectedSquaresArray = [20,9,29,13,51,41,79,73,35,58]; //VARIABLES used -- you do not need to change these //the square the player is currently on var playersPosition; //play is initially at START playersPosition = 0; //what they score when they roll the die var playersScore; //the index of the player's position in the special squares array or -1 var indexOfNumber; //MAIN PROGRAM //TODO add code here for parts (iii), (iv)(b), (v), and (vi) // start of question(iii) playersScore = rollDie(); document.write(' Sco ' + playersScore); playersPosition = playersScore + playersPosition; document.write(', Squa ' + playersPosition); indexOfNumber = findIndexOf(playersPosition, specialSquaresArray); if (indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; indexOfNumber = -1; } document.write('<BR>') // end of question(iii) // start of question(iv)(b) while(playersPosition<=80) { playersScore = rollDie() document.write(' Sco ' + playersScore) playersPosition = playersPosition + playersScore document.write(', Squa ' + playersPosition) indexOfNumber = findIndexOf(playersPosition, specialSquaresArray) if(indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; } document.write('<BR>'); } var countMoves = 0; while(countMoves <= 0) { document.write('You took ' + countMoves + ' moves to get out'); countMoves = countMoves + 1 } /*for (var countMoves = 0; countMoves < playersPosition; countMoves = countMoves + 1) { countMoves = countMoves + playersPosition; document.write('You took ' + countMoves + ' moves to get out'); }*/ // end of question(iv)(b) // start of question (v) /*if (playersPosition >=80) { document.write('The player is out'); }*/ // end of question (v) </SCRIPT> </HEAD> <BODY> </BODY> </HTML> Many thanks. Hello... Thanks for reading... I am getting an undefined error when i try to get a value from this array in the interior loop... Code: // This is the array I am trying to access AuditTable [0] = ["Visio Modifed date","Word Modified Date","User Status","User Comment","Last Audit","Audit Status","Audit Comment"] AuditTable [1] = ["11/23/2009 8:52:18 AM","missing","OK","user comment number 1","1/1/2009","ok","audit comment number 1"] AuditTable [2] = ["11/24/2009 12:21:19 AM","missing","Out of Date","Changes from 2008 not implemented","1/2/2009","Out of Date","needs update"] AuditTable [3] = ["11/22/2009 9:24:42 PM","missing","Incomplete","Document doesnt cover all possibilities","1/3/2009","Inadequate","needs update"] I have hard coded values and had success such as: Code: data = AuditTable[1][0] But when I put the vars associated with the loop in I get an undefined error - AuditTable[i] is undefined: Code: // produces error data = AuditTable[i][j] //Works but retrieves wrong data data = AuditTable[j][i] //Works but retrieves wrong data data = AuditTable[1][i] //Works but retrieves wrong data data = AuditTable[j][2] I must be trying to access the array incorrectly or something... I have defined all the vars, and tried many combinations, alerted the values of both vars so I can prove it is not a scope issue... Am I missing something obvious? Thanks much... Code: var reportArray=new Array(); var reportData, title, subTitle, data; for(i in parmarray)// loop thru AuditTable array and get values { title = '<div style="font-family:verdana; font-size:14px; font-weight:bold; margin:25px 0px 5px 30px">'; title += namearray[i][0]; title += '</div>'; reportArray.push(title);//Take compiled variable value and put it into array for(j=0; j < AuditTable[0].length; j++)// loop thru AuditTable array and get values { subTitle = AuditTable[0][j];//points to first row of AuditTable where the labels are data = AuditTable[1][0];//points to the current row where actual data is html = i + j +'<div style="font-family:verdana; font-size:12px; color:#696969; font-weight:bold; margin-left:30px;">'; html += subTitle; html += '</div><div style="font-family:verdana; font-size:12px; color:#a9a9a9; margin-left:30px; margin-bottom:10px">'; html += data; html += "</div>"; reportArray.push(html);// put results into array } } it wont loop, as long as you enter something in the name field it will submit. also how do i stop from submitting if all fields are not filled out? any help will be appreciated) ====== function checkForm(form) { var len = form.elements.length; var h=0; for (h=0; h<=len; h++){ if ((form.elements[h].value==null) || (form.elements[h].value=="")){ alert("Please enter "+document.myForm.elements[h].name); document.myForm.elements[h].focus(); return false; } return true; } } ===body-== <FORM NAME="myForm" METHOD="post" ACTION="http://ss1.prosofttraining.com/cgi-bin/process.pl"> Name:<BR> <INPUT TYPE="text" size="30" NAME="name"><br> Email address:<BR> <INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br> Phone number:<BR> <INPUT TYPE="text" size="30" NAME="phone number"><br> Fax number:<BR> <INPUT TYPE="text" size="30" NAME="fax number"><p> <INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);"> <INPUT TYPE="reset" VALUE="Reset Form"> </FORM> Hi, I am doing some studying and we was to create a small loop using either the for loop, while loop or do while loop. I chose to do the for loop because it was easier to understand, but I want to know how to do the same using the while loop. Here is the for loop I have, but I cant figure out how to change to while loop. Code: for (var i = 0; i < 5; ++i) { for (var j = i; j < 5; ++j) { document.write(j + ""); } document.write("<br />"); } output is equal to: 01234 1234 234 34 4 How do you make the same using a while loop? I have a form that shows or hides divs based on what is chosen in a dropdown. There are 4 divs but only one is shown and the other 3 hidden based on dropdown selection. Inside each div are checkboxes with items for sale. I want to reset the checkboxes to unchecked and the line total values to 0 if the div is hidden. I've got the checkboxes to reset but I can't figure out how to set the line total values to 0 (There are 14 total so I'm trying to loop thru all of them and reset them.) This is what I have in the loop Code: for (var i = 0; i < form.elements.length; i++ ) { if (form.elements[i].type == 'checkbox') { form.elements[i].checked = false; } } // set line_totals to 0 for (var j = 0; j< form.elements.length; j++ ) { if (form.elements [j].name.substring(0,10) == 'line_total') { form.elements[j].value = ''; } } For those who read my other thread I finally scratched together the code to take a value from an XML file and add it to a select box as an option. Ofcourse it only does it once so I need to loop it. It's kinda complex though, here's a function line to add one option: addOption(document.people_form.People,name2,office2) And here's the code in the head: <script type="text/javascript"> //load xml file if (window.ActiveXObject){ var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async=false; //Enforce download of XML file first. IE only. } else if (document.implementation && document.implementation.createDocument) var xmlDoc= document.implementation.createDocument("","doc",null); if (typeof xmlDoc!="undefined") xmlDoc.load("namedata.xml"); //Regular expression used to match any non-whitespace character var notWhitespace = /\S/ function getnames(){ //Cache "messages" element of xml file var nameobj=xmlDoc.getElementsByTagName("list")[0] //REMOVE white spaces in XML file. Intended mainly for NS6/Mozilla for (i=0;i<nameobj.childNodes.length;i++){ if ((nameobj.childNodes[i].nodeType == 3)&& (!notWhitespace.test(nameobj.childNodes[i].nodeValue))) { // that is, if it's a whitespace text node nameobj.removeChild(msgobj.childNodes[i]) i-- } } } if (typeof xmlDoc!="undefined"){ if (window.ActiveXObject) //if IE, simply execute script (due to async prop). getnames() else //else if NS6, execute script when XML object has loaded xmlDoc.onload=getnames } var name2=xmlDoc.getElementsByTagName("name")[0].firstChild.nodeValue; var office2=xmlDoc.getElementsByTagName("office")[0].firstChild.nodeValue; var officePH2=xmlDoc.getElementsByTagName("officePH")[0].firstChild.nodeValue; var mobile2=xmlDoc.getElementsByTagName("mobile")[0].firstChild.nodeValue; var email2=xmlDoc.getElementsByTagName("email")[0].firstChild.nodeValue; </script> <script type="text/javascript"> function addOption(selectbox,text,value ) { var optn = document.createElement("OPTION"); optn.text = text; optn.value = value; selectbox.options.add(optn); } </script> Could anyone give me a pointer on how to loop this so that it loads one option after another from the XML file? Thanks. Hello, I recently purchased a JavaScript book, and I am confused by one of it's examples. I was wondering if anybody could answer my question. Here is the example: for (loopCounter = 1; loopCounter<= 3; loopCounter++) { //execute this code } Now, what I need help with is the variable part. The book goes on to say: ""To keep track of how many times you have looped through the code, you need a variable to keep count" My question is: Why does the variable have the value of one and not another number? I'm very very new to JS, I understand that the loopCounter has to be les than or equal to 3 for the code to execute, and also that it is incremented by one each loop, but the book is not clear on why the value of the variable has been set to 1. If anybody could answer this question I would be very grateful, I hate moving onto the next stage of a book if I do not completely understand the previous topics. Thank you in advance Hi All, im trying to to use a for loop to loop through a drop down list of users and if there is a match between the user logged in and the drop down list i want to enable two fields, if the user logged in isnt in the drop down list i want to disable the two fields, but im having trouble looping through, iv tried ".value" with no avail.. heres my Script Code: var RequestingUser = document.getElementById('JoinersLeaversContent_cmbRequestingUser').text; var Authorisers = document.getElementById('JoinersLeaversContent_ddlAuthoriseId'); for (var i = 0; i < Authorisers.length; i++) { if (RequestingUser.text == Authorisers.value) { document.getElementById('JoinersLeaversContent_txtAuthoriserSig').disabled = false; document.getElementById('JoinersLeaversContent_txtDateSignedOff').disabled = false; } else { document.getElementById('JoinersLeaversContent_txtAuthoriserSig').disabled = true; document.getElementById('JoinersLeaversContent_txtDateSignedOff').disabled = true; } } So just to be clear, if the user logged in appears in the drop down box i want to enable the two fields, if they dont appear i want to disable the two fields Please help. Thank you Hello all. I am faitly new at programming and have run into a little problem. I want to create a script that creates 2 random numbers, stored in 2 different variables and then compare them to eachother. there is two possible outcome of that comparison, either they are different or they are alike. If they are different i want to randomize a new set or numbers and make a other comparement, also to keep track on how many times i have created numbers. If they are alike i want to display the numbers and how many tries it took to get a matching pair. atm it looks like this <html> <body> <script> var x=(Math.floor(Math.random()*6)+1); var y=(Math.floor(Math.random()*6)+1); //creates two random int between 1 and 6 var throws = 1; //keep tabs on how many times we have thrown the dices if(x!=y) { x=(Math.floor(Math.random()*6)+1); y=(Math.floor(Math.random()*6)+1); throws=throws+1 }else{ document.write("you have rolled a pair. Dice 1 is: " +x +" and Dice 2 is: " +y +" and it took " +throws +" tries to get a pair."); } </script> </body> </html> How to get that into a loop? a really confused newbie scripter Hey guys i've just been following a few tutorials and learnt how to do a for loop and a while loop, what is the major difference between the two? they seem quite similar? I know while loops are laid out a hell of a lot easier in my opinion!
I have the following code which is almost completely working the way I need it to with the exception of the "downloadFile" value... Code: /*Regex list of download file extensions, pipe and backslash delimited. Looks for the period before the file type so it will work on download links with query parameters after it */ var downloadTypes = /\.pdf|\.doc|\.xls|\.zip|\.csv|\.ppt|\.rtf|\.pptx|\.docx|\.xlsx|\.wmv|\.mpg|\.exe|\.mp3|\.rar|\.wav/i; /*Regex list of on-site domains, pipe and backslash delimited. */ var onsiteDomains = /\mytestdomain1\.com|\mytestdomain2\.com|javascript|#/i; /*Used to unobtrusivly add events to objects*/ function unobtrusiveAddEvent (element,event,fn) { var old = (element[event]) ? element[event] : function () {}; element[event] = function () {fn(); old();}; } var links = document.links; if ( links ){ for(var i=0; i<links.length; i++) { if( links[i].href.match(downloadTypes) ){ unobtrusiveAddEvent( links[i], 'onclick' , function() { ntptEventTag('ev=download&eventPage=Download From: ' + escape( wa.currentDomain + wa.currentURL ) + '& downloadFile=' + escape( links[i] ) ); }); } if( !links[i].href.match(onsiteDomains) ){ unobtrusiveAddEvent( links[i], 'onclick' , function() { ntptEventTag('lk=1&ev=Exit Link'); }); } } } ...how do I grab the value of the href that was just clicked? links[i] is not working (it's just grabbing the href value of the last href in the loop). I am missing something simple for sure. Can anyone point out what I am missing? Thanks! Hi all, I have a problem where I'm trying to load data into multiple divs. They are payslips, so p1, goes into january, p2 into febuary etc. I want to onLoad them all so when the page is loaded they are all displayed. Every time I try this, the loop automatically goes to the last iteration, 6 in this example, so the only div that is loaded is p6. Here is my code: function replace(slip, year) { // table contains either 'bank' or 'intranet' xmlHttpReq.open("POST", "do_payslips_ajax.php", true); xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlHttpReq.onreadystatechange=function() { if(xmlHttpReq.readyState == 4) { document.getElementById("p" + slip).innerHTML = xmlHttpReq.responseText; } } xmlHttpReq.send(getquery(slip,year)); } function getquery(slip,year) { strQuery = "weekmonth=" + slip + "." + year; return strQuery; } function loadpayslips(year) { for (slip=1; slip<=6; slip++) { replace(slip, year); } } <label> <body onload = loadpayslips(11)> search</a> </label> <div id="p1"> /div> <div id="p2"> month 2</div> <div id="p3"> month 5</div> etc.. Any help would be appreciated. Thanks Ok so I have these elements on my page: Code: <input type="text" size="5" name="val[]" value="'.$NotaMaxima.'"> I want to loop through each one and take their number add it to another number set in a variable elsewhere and then alert that number. The amount of these elements on the page changes constantly, so I can't count on that. It has to loop through each one to find the values. I tried this: Code: var els,i,asig; els=document.getElementsByTagName('val'); for(i in els) { asig = parseInt(els[i].value) - parseInt(asig); } alert(asig); But no go, any ideas? Hi friends i have a gridview with id gvcustomers...it has tow columns latitudes and longitudes i want to loop thoiugh the gridview on the client side and get the values like this...but the problem i have is mentioned in the comments below var theGridView = document.getElementById('<%=gvCustomers.ClientID%>'); for (var rowCount = 1; rowCount < theGridView.rows.length; rowCount++) { /// the numbers in the array are lats and longs which are hard //coded...this where i want the latitude and longitude colmn to come.. var latlongs = new Array(new VELatLong(45, -110), new VELatLong(45, -114), new VELatLong(45, -90), new VELatLong(45, -95)); // } How can i achieve this...thank you akpaga Senior Apprentice Senior Apprentice LTD Bronze - Rating: 3 Posts: 167 Joined: Wed May 27, 2009 4:15 pm Unrated |