JavaScript - Nested If Statement Nightmare.
I have a nested if that is not working, well I have two which are pretty much the same code apart from one has more conditions. The one with the least does not work.
It is basically a quick password checker to see if the typed password matches the previously typed and then display an image according. Code: function checkPass(id){ var pass = document.getElementById(id).value; if(pass == "") { notValid(id); } else if(id == "pwd2" && pass !== document.getElementById("pass").value || document.getElementById("pass").value == "") { notValid(id); } else { isValid(id); }; }; If it is blank it calls notvalid and if the second if flags it calls notvalid however if it is ok then it does not do the else. Any ideas?? Thanks. Similar TutorialsHey All, I've been poking away at what should be very simple code, but is becoming a nightmare. I have an iframe that the user uses to enter certain information, the iframe loads contiguous urls that do server side scripting and store information, so a total of 12 php files are run through until the user comes to the end of the information gathering session. I then want to give them the option to go back and review the information they gave me, OR submit the information (which I already have anyways). All I want the submit button on this last document to do is to set the style of the div that contains the iframe to display='none'. I have tried everything I can think of to do it, but I can seem to get the darn thing to call an element from the parent window on the inside. I've used "window.parent" and "parentNode" and they absolutely don't work. Any help would be greatly appreciated. As a newbie, I've been combining scripts and adjusting them to create a page that allows viewers to choose from different visual elements of a leaf that will be used to search a database. There are rollovers for each anchor dropdown, and a center image that is in layers to "assemble" the leaf. But I've run into a logistical nightmare and I'm not sure which is the best way to handle this. if variations were slight, i would have no problem. But to show some characteristics I need to know what one or two underlying images were as well. In other words, if I am choosing borders, and I have a round image. The border would have to know to put a round scalloped border - not a square one. (And if somebody goes back to change the shape, I would need the border to automatically know to change to a square scalloped border) Can I build conditionals within the layers? Or does it need to be inline with the image? is there another way to do this before my script becomes a disaster when I try to accommodate for numerous variations. Can I get a snippet or two of code to send me in the right direction? maybe there's some precreated script for this? (I can dream!) I hope that makes some sense. Here's the page that I'm working on. http://www.mergecreate.com/test25n.html Hello everyone, I am using javascript and I have a radio button that the user selects and I have a function to see which button was selected, but i'm trying to use the return of that if statement in another statement. Basically another part of the function is dependent on what the user selects in the radio button. Here is what I have so far (I have some things in there that might not work because i'm trying to figure out what works): Code: <script type="text/javascript"> function getSelectedRadio() { len = document.dates.dep.length // returns the array number of the selected radio button or -1 if no button is selected if (document.dates.dep[0]) { // if the button group is an array (one button is not an array) for (var i=0; i<len; i++) { if (document.dates.dep[i].checked) { return i } } } else { if (document.dates.dep.checked) { return 0; } // if the one button is checked, return zero } // if we get to this point, no radio button is selected return -1; } function Calculate() { var i = getSelectedRadio(); if (i == -1) { alert("Please select if Marine entered Delayed Entry Program"); } else { if (document.dates.dep[i]) { return document.dates.dep[i].value; } else { return document.dates.dep.value; } } if (document.dates.yearDEAF.value < 1985 && document.dates.monthDEAF.value < 01 && document.dates.dayDEAF.value < 01 && first return from above ) { document.dates.yearDEP.value = (document.dates.yearDEAF.value); document.dates.monthDEP.value = (document.dates.monthDEAF.value); document.dates.dayDEP.value = (document.dates.dayDEAF.value); document.dates.yearPEBD.value = (document.dates.yearDEAF.value); document.dates.monthPEBD.value = (document.dates.monthDEAF.value); document.dates.dayPEBD.value = (document.dates.dayDEAF.value); } else if (document.dates.yearDEAF.value < 1985 && document.dates.monthDEAF.value < 01 && document.dates.dayDEAF.value < 01 && second return from above ) { document.dates.yearPEBD.value = (document.dates.yearAFADBD.value); document.dates.monthPEBD.value = (document.dates.monthAFADBD.value); document.dates.dayPEBD.value = (document.dates.dayAFADBD.value); document.dates.yearDEP.value = "N/A"; document.dates.monthDEP.value = "N/A"; document.dates.dayDEP.value = "N/A"; } } </script> I color coded in red the returns i'm trying to reference and where they need to be. Is this possible, and if so how can I do it? I haven't been able to find anything on the internet so far. Any help is greatly appreciated! Hello. I was wondering if there is a way to call a second Javascript function from within the first. For example: <script>...call first function...</script> Inside first function: If (a==1) <script>...call second function...</script> else (a==2) <script>...call third function...</script> My thinking as to why I would need this is because I need to access two different Google Maps API codes. If that isn't possible, does anyone have any other suggestions? Hey Guys, I'm currently a seasoned programmer who is in a programming class at my school. We're currently learning advanced JavaScript, and we're on the topic of nested loops. After teaching us about for and while loops, my teacher gave us a little puzzle to solve. It's kind of difficult to explain, but I'll give you guys my current code and what it outputs. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Word Reversal</title> <script type="text/javascript"> var ask = prompt("How many words do you want?",""); while (ask < "1") { alert("You have to have at least one word!"); var ask = prompt("How many words do you want?",""); } var num = parseInt(ask) + 1; var final = ""; for (var i=1; i < num; i++) { var word = prompt("What's word " + i + "?"); final = final + "Word " + i +": " + word + "<br/>"; } </script> </head> <body> <script type="text/javascript"> document.writeln(final); </script> </body> </html> The current output, when the user wants two words, and word 1 is one and word 2 is two, comes out to be: Code: Word 1: one Word 2: two Which is great, but the only problem is, this is what the output's supposed to be: Code: Word 2: two Word 1: one I'm stumped. I've had numerous programming challenges in my life which I've solved, but I'm not sure where to go next on this one. The script is supposed to use a nested loop, but what goes in what loop to reverse the order of the user's input? I asked my teacher for help, but he told me "Ask someone else." I asked another seasoned programmer in my class, who was just about as stumped as I was, so I went back to my teacher. "Well, ask another person" he replied. And can you believe this guy has a Master's Degree of Computer Science? So I'm asking you guys: the community. I hope someone will be able to help me. On top of that, I have to help and tutor two special education students in my class on this kind of stuff during class, and they can't get the project done until I get it done, as they learn from analyzing and copying my work (which my teacher told me to do). They get upset when they have nothing to code, and they end up goofing off the entire period, or using it as a study hall. I need to get them back on track, so we can move on to the next project. Please help me with this code - it would be greatly appreciated. Thank you! This may be a basic programing problem but I am writing a function to validate a form using a bunch of else-if statements and encounters a problem when I use nested if/else-if statements. It will not continue on to the next else-if, after it returns false. Code: // to check each entry on the form and alert user if entry is invalid. function checkform(){ var checkssn = /(\d{3})-(\d{2})-(\d{4})/; var checkphone = /(\d{3})-(\d{4})/; var checkname = /[a-zA-Z]+(\.|,|\s)*/; var checkzip = /(^967|^968)\d{2}(-\d{4})?$/; // check to see if user have selected an Election if (!document.f1.elections[0].checked && !document.f1.elections[1].checked && !document.f1.elections[2].checked && !document.f1.elections[3].checked) { window.alert("Please select an Election!") return false; // check to see if user entered a valid SSN } else if ( checkssn.test(document.f1.ssn.value) == false){ window.alert("[1]. Please enter a valid social security number in the format ddd-dd-ddd"); return false; // check to see if user entered a valid home telephone number or business telephone number }else if ( document.f1.home_phone.value == '' && document.f1.business_phone.value == '') { window.alert("[4]. Please enter a Home or Business telephone number!") return false; } else if ( document.f1.home_phone.value != ''){ if (checkphone.test(document.f1.home_phone.value) == false){ window.alert("[4]. Please enter a valid home phone number in the format ddd-ddd"); return false; } } else if ( document.f1.business_phone.value != ''){ if ( checkphone.test(document.f1.business_phone.value) == false){ window.alert("[4]. Please enter a valid business phone number in the format ddd-ddd"); return false; } // check to see if user entered a valid Name }else if ( checkname.test(document.f1.lastname.value) == false){ window.alert("[5]. Last Name can only consist of letters, periods(.), commas(,) and spaces"); return false; }else if ( checkname.test(document.f1.firstname.value) == false){ window.alert("[5]. First Name can only consist of letters, periods(.), commas(,) and spaces"); return false; The problem occurs when it validates the phone numbers. When a valid number is entered, it will not move to the next else-if statement to validate the name. It's been years since I program in Java/C, so I'm a bit rusty. Any help is appreciated. -Alex OK i'm trying to make an affiliate section for my page in javascript, I used double arrays and it's terribly coded. Please help. I'm new to this... Code: <html> <body> <script type="text/javascript"> var alley = new Array(); alley[0] = new Array( "http://stereo.b1.jcink.com/", "http://i49.tinypic.com/5klkb6.gif", "Stereo Wired" ); alley[1] = new Array ( "http://s1.zetaboards.com/N2010/", "http://sixpop.com/files/246/n2010.png", "N2010" ); alley[2] = new Array ( "http://theipodnation.net", "http://img15.imageshack.us/img15/1043/affiipod.png", "The Ipod Nation" ); for ( i = 3; i < alley.length; i++ ) { for ( m = 0; m < alley[i].length; m++ ) { document.write(" <a href='" + alley[i][m][0] + "'><img src='" + alley[i][m][1] + "' alt='" + alley[i][m][2] + "' /></a> ") } } </script> </body> </html> Hello codingforums.com! Right, this is probably going but such a stupid newbie thread but here goes.. I've finally got myself into gear to start learning javascript. I've been watching video tutorials, learning from websites and simply learning by error. I understand the concept of for loops, but the whole nested thing doesn't seem to click for some reason. I thought i understood and managed to write a piece of code that constantly writes '*' across the screen. Could someone with some pretty damn good knowledge of javascript be able to walk me through step by step of my script to explain what actually is happening? It would help loads. here is the script, many thanks!! <script type="text/javascript"> var counter = 0; function writeStars(){ for(i=0;i<1;i++){ for(a=0;a<=counter;a++){ document.write("*"); } counter++ document.write("<br />"); } } setInterval("writeStars()", 200); </script> I'm trying to reuse some code in a different context to do a different job. The code to be reused contains hundreds of lines similar to a = new b.c.d(e,f) with different value for e and f. I need to create a new user defined object with the structure b.c.d. I've made numerous attempts along the lines of: Code: function d (e, f) { this.e = e; this.f = f; } function c () { this.d = d (e, f); } function b () { this.c = c; } var a = new b.c.d("test", "message"); with various permuations of functional declarations. However I get error message "Object expected" or "b.c.d is null or not an object" at the final line of the example. It works with the test line var a = new d("test", "message") but not when I start to build up the expression. How should I define of b.c.d? Hi I need help to finish this code with using nested if statements A price of a ticket to a passenger will be: First Class 500 Economy Class (with meal) 400 Economy Class (without meal) 200 How I can write a JavaScript code according to the following specifications: a. Read the class that the passenger wants to travel on. b. If the class is the first class, print the price of ticket. c. If the class is the economy class, ask the user if he/she wants a meal on the flight. Then print the price of the ticket according to the response of the passenger. The program should simply accept one possible strings the user enters; it is not required to work for all possible inputs such as First, first, FIRST or Yes , yes, YES. This is the code which I have been trying { var inputNum = prompt("Enter the class you want\n first class?\neconomy? :"); if (isNaN(inputNum)) { if (inputNum.match(/first class/)) { document.write("<h1><center>your Ticket is 500<\center><\h1>"); } else { prompt("<h1>if you want a meal on the flight press OK <\h1>"); document.write("<h1>your ticket is 400<h1>,"); } } I'm running into issues while trying to make some simple code to loop through and display different combinations of 3 colours. I want to show 3 boxes on screen and then loop through/increment each possible combination of colours. For simplicity's sake I'm trying to go from black to white in each box like this: (box1rgb/box2rgb/box3rgb) step 1: 000 000 000 step 2: 000 000 111 step 3: 000 000 222 . . . step 256: 000 000 255255255 step 257: 000 111 000 step 258: 000 111 111 step 259: 000 111 222 . . . step 512: 000 111 255255255 step 513: 000 222 000 step 514: 000 222 111 . etc. Yes, I know the thing will take a long time to complete! The colour is being set by the statement document.getElementById("box#").style.backgroundColor = "rgb(" + p1 + "," + p1 + "," + p1 + ")"; where p1 is the incrementing variable. Firstly I tried to do it using nested "for" loops. Code: for (p3=0;p3<=255;p3++) { document.getElementById("box03").style.backgroundColor = "rgb(" + p3 + "," + p3 + "," + p3 + ")"; for (p2=0;p2<=255;p2++) { document.getElementById("box02").style.backgroundColor = "rgb(" + p2 + "," + p2 + "," + p2 + ")"; for (p1=0;p1<=255;p1++) { document.getElementById("box01").style.backgroundColor = "rgb(" + p1 + "," + p1 + "," + p1 + ")"; } } } But of course the code executes far too rapidly for each combination to be seen. It all chewed up lots of CPU and nothing was smooth. To slow the process, I tried a single recursive loop using a timeout statement: Code: function loopandshow() { document.getElementById("box01").style.backgroundColor = "rgb(" + currentcolour + "," + currentcolour + "," + currentcolour + ")"; currentcolour += 1; if (currentcolour <= 255) window.setTimeout("loopandshow();", 20); } This worked smoothly for a single box but I couldn't work out how to nest this format 3 levels deep and have each level increment only when the deeper level had completed the cycle. Any advice would be gratefully appreciated. Thanks in advance. i am having trouble with a program for class hoping someone can point me in the right direction i am supposed to use nested for loops to output 2 seperate webpages one with the first pattern below and then another with the second pattern. Thanks for your help [x] [x][x] [x][x][x] [x][x][x][x] [x][x][x][x][x] [x][x][x][x][x][x] [x][x][x][x][x][x][x] [x][x][x][x][x][x][x][x] [x][x][x][x][x][x][x][x][x] [x][x][x][x][x][x][x][x][x][x] [O] [O][O] [O][O][O] [O][O][O][O] [O][O][O][O][O] [O][O][O][O][O][O] [O][O][O][O][O][O][O] [O][O][O][O][O][O][O][O] [O][O][O][O][O][O][O][O][O] [O][O][O][O][O][O][O][O][O][O] ************************** ************************** [O][O][O][O][O][O][O][O][O][O] [O][O][O][O][O][O][O][O][O] [O][O][O][O][O][O][O][O] [O][O][O][O][O][O][O] [O][O][O][O][O][O] [O][O][O][O][O] [O][O][O][O] [O][O][O] [O][O] [O] I have the below html. In the below code, I have an onmouseover and onmouseout on the parent DIV of three nested DIVs. Whenever I mouse INTO the nested DIVs, the onmouseout event fires for the outermost DIV. Is there a way to prevent this? <html> <head> <script language="JavaScript"> function mouseOnDiv() { alert("mouseon outerDiv"); event.cancelBubble = true; } function mouseOffDiv() { alert("mouseoff outerDiv"); event.cancelBubble = true; } </script> </head> <body> <div style="border:1px solid red; position:absolute" onmouseover="mouseOnDiv()" onmouseout="mouseOffDiv()"> This is some text <div style="border:1px solid blue; position:relative"> This is some text in the middle div <div style="border:1px solid green; position:relative"> <ul> <li>Item 1</li> </ul> </div> </div> </div> </body> </html> I'm having trouble getting this nested loop to work. It only outputs the last image and I want it to loop through the images. Code: function loadgallery (){ var picarray= new Array () picarray[0]="pic1.jpg" picarray[1]="pic2.jpg" picarray[2]="pic3.jpg" picarray[3]="pic4.jpg" picarray[4]="pic5.jpg" picarray[5]="pic6.jpg" for (j=0;j<picarray.length ;j++ ){ pic=picarray[j] var tdarray = document.getElementsByTagName("td"); for (i=0;i<tdarray.length;i++ ){ tdarray[i].innerHTML='<select name="select1"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option></select><img src="pics/'+picarray[j]+'">'; } } } window.onload=loadgallery; Hello, I have the following script, but I'd like to sort each nested array before it is written. How can I do this? I've tried putting Games.sort(); and Games[0].sort(); in different places, but it never seems to work. Code: var Games = new Array(); //PS3 Games[0] = new Array(); Games[0][0] = "ps3list"; Games[0][1] = "Uncharted: Among Thieves"; Games[0][2] = "Prince of Persia"; Games[0][3] = "Saboteur"; Games[0][4] = "Assassins Creed"; //Wii Games[1] = new Array(); Games[1][0] = "wiilist"; Games[1][1] = "Wii Play"; Games[1][2] = "Mario Party 8"; Games[1][3] = "Okami"; Games[1][4] = "Wii Sports"; function loadGames(){ for (i = 0; i < Games.length; i++) { var list = "<ul>"; for (j = 1; j < Games[i].length; j++) { list += "<li><input type = 'checkbox' class='checkbox' name = '" + Games[i][j] + "' />" + Games[i][j] + "</li>"; } list += "</ul>" document.getElementById(Games[i][0]).innerHTML = list; } } Sorry folks, Im not sure that I am using the correct terminology here. What i would like to do is sort an array based on the [SortBy] value, however this array is nested. For instance: ar.[SortBy]"PartNumber" ar.[0].[PartNumber]"123" ar.[0].[PartName]"Widget1" ar.[1].[PartNumber]"345" ar.[1].[PartName]"Widget2" ar.[2].[PartNumber]"456" ar.[2].[PartName]"Widget3" ar.[3].[PartNumber]"567" ar.[3].[PartName]"Widget4" Thanks! Hi i need a little help on a JavaScript program it ask the user for a keyboard character and a number of rows and columns to look like this RRRRR R___R R___R R___R RRRRR and also this in another program rrrrrr rrrrrr rrrrrr rrrrrr I currently have <html><body> <script type="text/javascript"> // Declare variables and constants var userInputText; // user input to go var numRow; // number of the rows var NumCol; // number of the columns var ES = ""; // empty string userInputText = prompt("Enter a keyboard character",ES); numRow = prompt("Enter the number of rows",ES); NumCol = prompt("Enter the number of columns",ES); //need a nested loop to draw the character box </script> </body> </html> if any one can help me finish this program i would appreciate it here is my function at the moment which gets some HTML: Code: function showRecent() { Ext.Ajax.request({ url: 'server.php?action=get', success: function(e) { var obj = Ext.util.JSON.decode(e.responseText); var pubs = obj.pubs; if (pubs) { var html = tpl.applyTemplate(pubs); Ext.getCmp('recentTab').update(html); } } }); } here is my HTML: Code: <div id="pubs" class="x-hidden-display"> <tpl for="."> <div class="detail"> <div class="clear"> <span class="span2 bottomright">{rsTown}</span> </div> <div class="clear"></div> </div> </tpl> <br/> <br/> <br/> </div> I'd like to show my data in a nested group list Please help?! I'm having a javascript problem with nested elements. Consider an example in which you have two nested elements with element 2 being inside of element 1 and only element 1 has an onmouseout event handler. <div style="position:relative;border:1px solid red;width:300px;height:300px" onmouseout="alert('whatever')"> //element 1 <div style="position:absolute;border:1px solid blue;left:50%;top:50%;margin-left:-50px;margin-top:-50px;width:100px;height:100px">//element 2 </div> </div> The 2 problems here are as follows: 1- Moving the mouse pointer over element 2 from element 1 causes a onmouseout with element 1. But this is a minor problem. 2- Moving the mouse pointer from element 2 back to element 1 causes a mouseout with ,I believe, element 2 even though there is no onmouseout event handler here. This is a major problem. Is problem #2 due to possibly an automatic inheritance of the onmouseover handler from element 1 onto element 2 OR is it the result of event capturing or what else? I can't tell either way. If it's due to inheritance how do you stop this from taking place? The strange thing is that tutorials give this kind of scenario with element 2 inside of element 1 with both elements having the same event handler but they don't say what happens in this case with just one element having a specific event handler. Thank you. Okay, I have another problem. I really can't figure out why it's not working in IE. The only problem I can think of would be using nested loops. Here's the part of the code that isn't working. It's not generating an error, it's just not returning anything. I know you guys hate when I post entire code, so I trimmed it down as much as I can. It's referring to an already stated xml document with xmlDoc. And it's goal is to return a table of rows that meet certain criteria. If you can see any syntax errors that explorer would not like, that's really what I'm asking for. Thanks in advance, Julian Code: var entries = Array.prototype.slice.call(arguments, 1); var headers = 0; for (var i=0;i<xmlDoc.getElementsByTagName('entry').length;i++) { var x = headers; headers += xmlDoc.getElementsByTagName('header').length; var id = xmlDoc.getElementsByTagName('entry')[i].getAttribute("id"); if (entries.indexOf(id) >= 0) { content += '<tr>'; for (x;x<headers;x++) { content += '<td>' + xmlDoc.getElementsByTagName('item')[x].firstChild.nodeValue + '<\/td>'; } } content += '<\/tr>'; } return content; |