JavaScript - Loop Elements By Name
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? Similar TutorialsHi again, I have written the follow code. It is meant to (when finished) output a table showing each member of the array PEOPLE. There Income ,there Tax bracket and there finally there total tax paid. The calulations in the if-else statements are correct. I have to create a loop that will go through the if else statements equal to the amount of the people in the array (This is no problem I have done this earlier) My problem is when I try to add each element (PEOPLE) to the table or there indivual tax outcomes. Can I create a loop and increment in the elements each iteration to put on the table?(for there names) As I am not meant to store each iteration,it is to write to the table each time. This is the code I'm working on with out the loop. [CODE]<html> <head> <script> PEOPLE = new Array ('Mr Dobbaleana','David Lai','Richard Watson','Leigh Brookshaw','Stijn Dekeyser'); BRACKET_LIMITS = new Array (0,6000,37000,80000,180000); MIN_TAX = new Array (0.00,0.00,4650.00,17550.00,54550.00); TAX_RATES = new Array (0.00,0.15,0.30,0.37,0.45); var taxBracket =0; var taxToPay =0; document.writeln ('<table border="2">'); document.writeln ('<tr>'); document.writeln ('<th>'+('Name')+'</th>'); document.writeln ('<th>'+('Income')+'</th>'); document.writeln ('<th>'+('Bracket')+'</th>'); document.writeln ('<th>'+('Tax')+'</th>'); document.writeln ('</tr>'); var currentPersonInRow = parseInt(prompt('Enter your income')); if (currentPersonInRow <= BRACKET_LIMITS[1]){ taxBracket=BRACKET_LIMITS.indexOf(0); taxToPay = (currentPersonInRow-BRACKET_LIMITS[0])*TAX_RATES[0]+MIN_TAX[0]; // will give total taxable income } else if (currentPersonInRow<=BRACKET_LIMITS[2]){ taxBracket=BRACKET_LIMITS.indexOf(6000); taxToPay = (currentPersonInRow-BRACKET_LIMITS[1])*TAX_RATES[1]+MIN_TAX[1]; // will give total taxable income } else if (currentPersonInRow<=BRACKET_LIMITS[3]){ taxBracket=BRACKET_LIMITS.indexOf(37000); taxToPay = (currentPersonInRow-BRACKET_LIMITS[2])*TAX_RATES[2]+MIN_TAX[2]; // will give total taxable income } else if (currentPersonInRow<=BRACKET_LIMITS[4]){ taxBracket=BRACKET_LIMITS.indexOf(80000); taxToPay = (currentPersonInRow-BRACKET_LIMITS[3])*TAX_RATES[3]+MIN_TAX[3]; // will give total taxable income } else { taxBracket=BRACKET_LIMITS.indexOf(180000); taxToPay = (currentPersonInRow-BRACKET_LIMITS[4])*TAX_RATES[4]+MIN_TAX[4]; // will give total taxable income } document.writeln ('<tr>'); document.writeln ('<td>'+(PEOPLE[0])+'</td>'); document.writeln ('<td>'+('$')+(currentPersonInRow)+'</td>'); document.writeln ('<td>'+(taxBracket)+'</td>'); document.writeln ('<td>'+('$')+(taxToPay)+'</td>'); document.writeln ('</tr>'); </script> </head> <body> </body> </html> [/ICODE] OK this is the code I wrote and it works but doesnt meet the assigment critera. Code: <html> <head> <script> PEOPLE = new Array ('Mr Dobbaleana','David Lai','Richard Watson','Leigh Brookshaw','Stijn Dekeyser'); BRACKET_LIMITS = new Array (0,6000,37000,80000,180000); MIN_TAX = new Array (0.00,0.00,4650.00,17550.00,54550.00); TAX_RATES = new Array (0.00,0.15,0.30,0.37,0.45); var personZero = parseFloat( prompt ((' Enter income for ')+(PEOPLE[0]),('0.00'))); var personOne = parseFloat (prompt ((' Enter income for ')+(PEOPLE[1]),('0.00'))); var personTwo = parseFloat (prompt ((' Enter income for ')+(PEOPLE[2]),('0.00'))); var personThree = parseFloat (prompt ((' Enter income for ')+(PEOPLE[3]),('0.00'))); var personFour = parseFloat(prompt ((' Enter income for ')+(PEOPLE[4]),('0.00'))); if ((personZero >= BRACKET_LIMITS[0])&&(personZero <= BRACKET_LIMITS[1])) { var cal1= (personZero-BRACKET_LIMITS[0]); var cal2= (cal1*TAX_RATES[0]); var totalTaxPaid = (cal2+MIN_TAX[0]); var taxBracketOfPeople1=0; alert(totalTaxPaid); } if ((personZero >= BRACKET_LIMITS[1])&&(personZero <= BRACKET_LIMITS[2])) { var cal1= (personZero-BRACKET_LIMITS[1]); var cal2= (cal1*TAX_RATES[1]); var totalTaxPaid = (cal2+MIN_TAX[1]); var taxBracketOfPeople1=1; alert(totalTaxPaid); } if ((personZero >= BRACKET_LIMITS[2])&&(personZero <= BRACKET_LIMITS[3])) { var cal1= (personZero-BRACKET_LIMITS[2]); var cal2= (cal1*TAX_RATES[2]); var totalTaxPaid = (cal2+MIN_TAX[2]); var taxBracketOfPeople1=2; alert(totalTaxPaid); } if ((personZero >= BRACKET_LIMITS[3])&&(personZero <= BRACKET_LIMITS[4])) { var cal1= (personZero-BRACKET_LIMITS[3]); var cal2= (cal1*TAX_RATES[3]); var totalTaxPaid = (cal2+MIN_TAX[3]); var taxBracketOfPeople1=3; alert(totalTaxPaid); } if ((personZero >= BRACKET_LIMITS[4])) { var cal1= (personZero-BRACKET_LIMITS[4]); var cal2= (cal1*TAX_RATES[4]); var totalTaxPaid = (cal2+MIN_TAX[4]); var taxBracketOfPeople1=4; alert(totalTaxPaid); } if ((personOne >= BRACKET_LIMITS[0])&&(personOne <= BRACKET_LIMITS[1])) { var cal1= (personOne-BRACKET_LIMITS[0]); var cal2= (cal1*TAX_RATES[0]); var totalTaxPaid1 = (cal2+MIN_TAX[0]); var taxBracketOfPeople2=0; alert(totalTaxPaid1); } if ((personOne >= BRACKET_LIMITS[1])&&(personOne <= BRACKET_LIMITS[2])) { var cal1= (personOne-BRACKET_LIMITS[1]); var cal2= (cal1*TAX_RATES[1]); var totalTaxPaid1 = (cal2+MIN_TAX[1]); var taxBracketOfPeople2=1; alert(totalTaxPaid1); } if ((personOne >= BRACKET_LIMITS[2])&&(personOne <= BRACKET_LIMITS[3])) { var cal1= (personOne-BRACKET_LIMITS[2]); var cal2= (cal1*TAX_RATES[2]); var totalTaxPaid1 = (cal2+MIN_TAX[2]); var taxBracketOfPeople2=2; alert(totalTaxPaid1); } if ((personOne >= BRACKET_LIMITS[3])&&(personOne <= BRACKET_LIMITS[4])) { var cal1= (personOne-BRACKET_LIMITS[3]); var cal2= (cal1*TAX_RATES[3]); var totalTaxPaid1 = (cal2+MIN_TAX[3]); var taxBracketOfPeople2=3; alert(totalTaxPaid1); } if ((personOne >= BRACKET_LIMITS[4])) { var cal1= (personOne-BRACKET_LIMITS[4]); var cal2= (cal1*TAX_RATES[4]); var totalTaxPaid1 = (cal2+MIN_TAX[4]); var taxBracketOfPeople2=4; alert(totalTaxPaid1); } if ((personTwo >= BRACKET_LIMITS[0])&&(personTwo <= BRACKET_LIMITS[1])) { var cal1= (personTwo-BRACKET_LIMITS[0]); var cal2= (cal1*TAX_RATES[0]); var totalTaxPaid2 = (cal2+MIN_TAX[0]); var taxBracketOfPeople3=0; alert(totalTaxPaid2); } if ((personTwo >= BRACKET_LIMITS[1])&&(personTwo <= BRACKET_LIMITS[2])) { var cal1= (personTwo-BRACKET_LIMITS[1]); var cal2= (cal1*TAX_RATES[1]); var totalTaxPaid2 = (cal2+MIN_TAX[1]); var taxBracketOfPeople3=1; alert(totalTaxPaid2); } if ((personTwo >= BRACKET_LIMITS[2])&&(personTwo <= BRACKET_LIMITS[3])) { var cal1= (personTwo-BRACKET_LIMITS[2]); var cal2= (cal1*TAX_RATES[2]); var totalTaxPaid2 = (cal2+MIN_TAX[2]); var taxBracketOfPeople3=2; alert(totalTaxPaid2); } if ((personTwo >= BRACKET_LIMITS[3])&&(personTwo <= BRACKET_LIMITS[4])) { var cal1= (personTwo-BRACKET_LIMITS[3]); var cal2= (cal1*TAX_RATES[3]); var totalTaxPaid2 = (cal2+MIN_TAX[3]); var taxBracketOfPeople3=3; alert(totalTaxPaid2); } if ((personTwo >= BRACKET_LIMITS[4])) { var cal1= (personTwo-BRACKET_LIMITS[4]); var cal2= (cal1*TAX_RATES[4]); var totalTaxPaid2 = (cal2+MIN_TAX[4]); var taxBracketOfPeople3=4; alert(totalTaxPaid2); } if ((personThree >= BRACKET_LIMITS[0])&&(personThree <= BRACKET_LIMITS[1])) { var cal1= (personThree-BRACKET_LIMITS[0]); var cal2= (cal1*TAX_RATES[0]); var totalTaxPaid3 = (cal2+MIN_TAX[0]); var taxBracketOfPeople4=0; alert(totalTaxPaid3); } if ((personThree >= BRACKET_LIMITS[1])&&(personThree <= BRACKET_LIMITS[2])) { var cal1= (personThree-BRACKET_LIMITS[1]); var cal2= (cal1*TAX_RATES[1]); var totalTaxPaid3 = (cal2+MIN_TAX[1]); var taxBracketOfPeople4=1; alert(totalTaxPaid3); } if ((personThree >= BRACKET_LIMITS[2])&&(personThree <= BRACKET_LIMITS[3])) { var cal1= (personThree-BRACKET_LIMITS[2]); var cal2= (cal1*TAX_RATES[2]); var totalTaxPaid3 = (cal2+MIN_TAX[2]); var taxBracketOfPeople4=2; alert(totalTaxPaid3); } if ((personThree >= BRACKET_LIMITS[3])&&(personThree <= BRACKET_LIMITS[4])) { var cal1= (personThree-BRACKET_LIMITS[3]); var cal2= (cal1*TAX_RATES[3]); var totalTaxPaid3 = (cal2+MIN_TAX[3]); var taxBracketOfPeople4=3; alert(totalTaxPaid3); } if ((personThree >= BRACKET_LIMITS[4])) { var cal1= (personThree-BRACKET_LIMITS[4]); var cal2= (cal1*TAX_RATES[4]); var totalTaxPaid3 = (cal2+MIN_TAX[4]); var taxBracketOfPeople4=4; alert(totalTaxPaid3); } if ((personFour >= BRACKET_LIMITS[0])&&(personFour <= BRACKET_LIMITS[1])) { var cal1= (personFour-BRACKET_LIMITS[0]); var cal2= (cal1*TAX_RATES[0]); var totalTaxPaid4 = (cal2+MIN_TAX[0]); var taxBracketOfPeople5=0; alert(totalTaxPaid4); } if ((personFour >= BRACKET_LIMITS[1])&&(personFour <= BRACKET_LIMITS[2])) { var cal1= (personFour-BRACKET_LIMITS[1]); var cal2= (cal1*TAX_RATES[1]); var totalTaxPaid4 = (cal2+MIN_TAX[1]); var taxBracketOfPeople5=1; alert(totalTaxPaid4); } if ((personFour >= BRACKET_LIMITS[2])&&(personFour <= BRACKET_LIMITS[3])) { var cal1= (personFour-BRACKET_LIMITS[2]); var cal2= (cal1*TAX_RATES[2]); var totalTaxPaid4 = (cal2+MIN_TAX[2]); var taxBracketOfPeople5=2; alert(totalTaxPaid4); } if ((personFour >= BRACKET_LIMITS[3])&&(personFour <= BRACKET_LIMITS[4])) { var cal1= (personFour-BRACKET_LIMITS[3]); var cal2= (cal1*TAX_RATES[3]); var totalTaxPaid4 = (cal2+MIN_TAX[3]); var taxBracketOfPeople5=3; alert(totalTaxPaid4); } if ((personFour >= BRACKET_LIMITS[4])) { var cal1= (personFour-BRACKET_LIMITS[4]); var cal2= (cal1*TAX_RATES[4]); var totalTaxPaid4 = (cal2+MIN_TAX[4]); var taxBracketOfPeople5=4; alert(totalTaxPaid4); } </script> </head> <body> <script> document.writeln ('<table border="2">'); document.writeln ('<tr>'); document.writeln ('<th>'+('Name')+'</th>'); document.writeln ('<th>'+('Income')+'</th>'); document.writeln ('<th>'+('Bracket')+'</th>'); document.writeln ('<th>'+('Tax')+'</th>'); document.writeln ('</tr>'); document.writeln ('<tr>'); document.writeln ('<td>'+(PEOPLE[0])+'</td>'); document.writeln ('<td>'+('$')+(personZero)+'</td>'); document.writeln ('<td>'+(taxBracketOfPeople1)+'</td>'); document.writeln ('<td>'+('$')+(totalTaxPaid)+'</td>'); document.writeln ('</tr>'); document.writeln ('<tr>'); document.writeln ('<td>'+(PEOPLE[1])+'</td>'); document.writeln ('<td>'+(personOne)+'</td>'); document.writeln ('<td>'+(taxBracketOfPeople2)+'</td>'); document.writeln ('<td>'+(totalTaxPaid1)+'</td>'); document.writeln ('</tr>'); document.writeln ('<tr>'); document.writeln ('<td>'+(PEOPLE[2])+'</td>'); document.writeln ('<td>'+(personTwo)+'</td>'); document.writeln ('<td>'+(taxBracketOfPeople3)+'</td>'); document.writeln ('<td>'+(totalTaxPaid2)+'</td>'); document.writeln ('</tr>'); document.writeln ('<tr>'); document.writeln ('<td>'+(PEOPLE[3])+'</td>'); document.writeln ('<td>'+(personThree)+'</td>'); document.writeln ('<td>'+(taxBracketOfPeople4)+'</td>'); document.writeln ('<td>'+(totalTaxPaid3)+'</td>'); document.writeln ('</tr>'); document.writeln ('<tr>'); document.writeln ('<td>'+(PEOPLE[4])+'</td>'); document.writeln ('<td>'+(personFour)+'</td>'); document.writeln ('<td>'+(taxBracketOfPeople5)+'</td>'); document.writeln ('<td>'+(totalTaxPaid4)+'</td>'); document.writeln ('</tr>'); document.writeln('</table>'); </script> </body> </html> Hope that wasnt to confusing Thanks heaps Shaynedarcy Hi all. I have a form named "theForm". How can I loop through this form elements that have an "id" ATTRIBUTE to them and then populate my ids array? var ids = new Array; for(i=0; i<document.theForm.elements.length; i++) { IF ELEMENT HAS AN ID ATTRIBUTE POPULATE ids array } I am trying to develop a function that creates a certain number of form elements based on a certain number that a user inputs. It does not do what I want it to do (obviously). The problem lies within the TextBoxAppear() function. The function worked when I tested it by adding just text (document.getElementByID('leftcolumn').innerHTML = "<p>test function</p>" so I know for a fact whatever I added to the function is the problem. What has been added to the function and needs fixing is in BOLD Code: <!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>Exercise 4</title> <style type = "text/css"> #leftcolumn { width: 300px; border: 1px solid red; float: left} #rightcolumn { width: 300px; border: 1px solid red; float: left} </style> <script> function start() { var button = document.getElementById( "submitButton" ); button.addEventListener( "click", TextBoxAppear, false ); } function TextBoxAppear() { var numberOfValuesInput = document.getElementByID( 'NumberOfValuesField' ); var numberOfValues = parseFloat( numberOfValuesInput.value ); var textBoxCreation = "<form action ="http://www.deitel.com"><p>"; for ( var i = 1; i < numberOfValues; ++i ) { textBoxCreation += "<label>Value" + i + ":<input id = 'Value" + i + "' type = 'text'></label>"; } textBoxCreation += "<input id = "calculateButton" type = "button" value = "Calculate"></p></form> document.getElementById('leftcolumnn').innerHTML = textBoxCreation; } window.addEventListener( "load", start, false ); </script> </head> <body> <form action ="http://www.deitel.com"> <p><label>Number of values to be calculated: <input id = "numberOfValuesField" type = "text"></label> <input id = "submitButton" type = "button" value = "Submit"></p> </form> <div id ="leftcolumn"><p>test left column</p></div> <div id ="rightcolumn"><p>test right column</p></div> </body> </html> I wrote js functions to reset a php form (multiple questions). The below works: Code: function resetForm(){ resetGroup(document.forms[0].answer1); resetGroup(document.forms[0].answer2); } Answer1 and answer2 are the elements of $_POST array. (<input name="answer1"> in php). In this example, I tried with only two questions, but I have up to 35 questions in one form. Instead of writing the above resetGroup() 35 times, I want to for-loop it. I tried Code: function resetForm(){ for (var i=1; i<3; i++){ resetGroup(document.forms[0]."answer"+i); } That didn't work. Could someone help me to make the loop work? Or would someone have better or simpler idea? Thanks. 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? Ok so I have these Input boxes and select boxes on my form. I have them input this way: Code: <input type="text" name="monto[]"> So I can then parse the many that get added and removed when I submit the form, this way PHP see's them as an array. Now I have used this in the past to cycle through my inputs to check values and such on them, but with these [] it doesn't work. Code: var changeCheck = document.getElementsByName('check'); for(i=0; i<changeCheck.length; i++) { var enter = new Number(getEl('dueitem' + changeCheck[i].value)); if(changeCheck[i].checked == true) { final = enter + final; } } Is there a way to cycle all these elements when they are as []. Even if it's cycle them by name, though I never had a determined amount I always have the same names for the 12 different fields there are. Hi, I got a table with hundreds of rows...and I want the user to be able to hide a single one by clicking on the table row. How can I do this without typing in hundreds of ids like 1,2,3,4,5... Since you can't get elements by class and ids have to unique I'm not sure how to do this. Also the order of the rows will change when they get updated so it would end up being a mess of unordered ids. Thanks. Alright,ill go straight to the problem. I want to get all the elements with a certain tag.However i can only get the first one. my code: Code: function getTags(tag) { var x = document.getElementsByTagName(tag); var y = x.length; for(var i = 0; i <= y;i++) { return x[i]; } } Im working on a function where i need to return the active elements ID. the element will have class="main" id="1" onmouseover="showSub()"> Would someone be able to write me a simple function which simply puts the elements ID number in an alert box? I can figure out the rest i need from that . Thanks, Tom What am I doing wrong here. I'm trying to generate this code into my listOfSquares UL using javascript: Code: <a href="#" id="square0"><li class="square"></li></a> This is my complete code: Code: <html"> <head> <title>Squares</title> <style> li.square { width: 26px; height: 26px; border: 1px solid black; display: block; float: left; margin: 5px; background-color: #39F; } div#squares { width: 725px; margin: 50px; background-color: #CCC; float: left; } div#form { width: 700px; text-align: center; clear: both; margin: 50px 50px 0 50px; } </style> <script> <!-- function generateSquare() { var number = 0; var squareID = "square" + number; var container = document.getElementById('listOfSquares'); var linked = document.createElement('a'); linked.setAttribute('href', '#'); linked.setAttribute('id', squareID); container.insertBefore(linked, container.firstChild); addToElement(squareID); } function addToElement(elementID){ var new_element = document.createElement('li'); new_element.setAttribute('class', 'square'); document.getElementById(elementID).innerHTML=new_element; } //--> </script> </head> <div id="form"> <form> <input type="button" value="Generate Square" onclick="generateSquare()" /> </form> </div> <body> <div id="squares"> <ul id="listOfSquares"> </ul> </div> </body> </html> Hi, I am trying to display some xml elements that are formatted like this: Code: <line> <route> <dirs>1. Head west on Calzada Roosevelt</dirs> <time>4.6 km - about 15 mins</time> <dirs>2. Continue on Carretera Interamericana/Pan American Hwy</dirs> <time>15 km - about 12 mins</time> <dirs>3. Look for turnoff at San Lucas and follow signs from there</dirs> <time>13.5 km - about 15 mins</time> </route> </line> using this js: Code: for (var a = 0; a < lines.length; a++) { routeInfo = lines[a].getElementsByTagName("route"); for (var p = 0; p < routeInfo.length; p++) { var time = GXml.value(routeInfo[p].getElementsByTagName("time")[0]); var dirs = GXml.value(routeInfo[p].getElementsByTagName("dirs")[0]); way+='<b>'+dirs+'</b>'+'<br>'+time+'<br>'; ("way" eventually gets passed as the text to display) Which works OK (as you can see here if you select from Guatemala City to Antigua), but the problem is that it only shows the first set of directions, ie Code: <dirs>1. Head west on Calzada Roosevelt</dirs> <time>4.6 km - about 15 mins</time> I can see that this is because of the [0] in the getElementsByTagName - if I change it to 1 or 2 it shows the 2nd or 3rd set of directions. But I want it to show all of them... and I thought that being in a loop it would, but I'm obviously missing something. Any ideas? Thanks in advance. I have a webpage which has the prototype library in it as well as my own script. I just started on it, but I've already run into issues using the for... in loop. I'll admit, I'm a complete noob at javascript, so this is probably something pretty simple. Code: function prepareToolBar() { //define toolbar tool names var toolbar = [ 'line', 'circle', 'ellipse', 'square', 'rectangle', 'text']; for (var i in toolbar) { var tmp = document.createElement("p"); tmp.appendChild(document.createTextNode(toolbar[i])); document.body.appendChild(tmp); } } addLoadEvent(prepareToolBar); function addLoadEvent(func) { var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } Below is the output on the page from the function: Code: circle ellipse square rectangle text function (iterator, context) { var index = 0; iterator = iterator.bind(context); try { this._each(function (value) {iterator(value, index++);}); } catch (e) { if (e != $break) { throw e; } } return this; } function (number, iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var index = - number, slices = [], array = this.toArray(); while ((index += number) < array.length) { slices.push(array.slice(index, index + number)); } return slices.collect(iterator, context); } function (iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var result = true; this.each(function (value, index) {result = result && !!iterator(value, index);if (!result) {throw $break;}}); return result; } function (iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var result = false; this.each(function (value, index) {if ((result = !!iterator(value, index))) {throw $break;}}); return result; } function (iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var results = []; this.each(function (value, index) {results.push(iterator(value, index));}); return results; } function (iterator, context) { iterator = iterator.bind(context); var result; this.each(function (value, index) {if (iterator(value, index)) {result = value;throw $break;}}); return result; } function (iterator, context) { iterator = iterator.bind(context); var results = []; this.each(function (value, index) {if (iterator(value, index)) {results.push(value);}}); return results; } function (filter, iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var results = []; if (Object.isString(filter)) { filter = new RegExp(filter); } this.each(function (value, index) {if (filter.match(value)) {results.push(iterator(value, index));}}); return results; } function (object) { if (Object.isFunction(this.indexOf)) { if (this.indexOf(object) != -1) { return true; } } var found = false; this.each(function (value) {if (value == object) {found = true;throw $break;}}); return found; } function (number, fillWith) { fillWith = Object.isUndefined(fillWith) ? null : fillWith; return this.eachSlice(number, function (slice) {while (slice.length < number) {slice.push(fillWith);}return slice;}); } function (memo, iterator, context) { iterator = iterator.bind(context); this.each(function (value, index) {memo = iterator(memo, value, index);}); return memo; } function (method) { var args = $A(arguments).slice(1); return this.map(function (value) {return value[method].apply(value, args);}); } function (iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var result; this.each(function (value, index) {value = iterator(value, index);if (result == null || value >= result) {result = value;}}); return result; } function (iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var result; this.each(function (value, index) {value = iterator(value, index);if (result == null || value < result) {result = value;}}); return result; } function (iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var trues = [], falses = []; this.each(function (value, index) {(iterator(value, index) ? trues : falses).push(value);}); return [trues, falses]; } function (property) { var results = []; this.each(function (value) {results.push(value[property]);}); return results; } function (iterator, context) { iterator = iterator.bind(context); var results = []; this.each(function (value, index) {if (!iterator(value, index)) {results.push(value);}}); return results; } function (iterator, context) { iterator = iterator.bind(context); return this.map(function (value, index) {return {value: value, criteria: iterator(value, index)};}).sort(function (left, right) {var a = left.criteria, b = right.criteria;return a < b ? -1 : a > b ? 1 : 0;}).pluck("value"); } function () { return [].concat(this); } function () { var iterator = Prototype.K, args = $A(arguments); if (Object.isFunction(args.last())) { iterator = args.pop(); } var collections = [this].concat(args).map($A); return this.map(function (value, index) {return iterator(collections.pluck(index));}); } function () { return this.length; } function () { return "[" + this.map(Object.inspect).join(", ") + "]"; } function (iterator, context) { iterator = iterator.bind(context); var result; this.each(function (value, index) {if (iterator(value, index)) {result = value;throw $break;}}); return result; } function (iterator, context) { iterator = iterator.bind(context); var results = []; this.each(function (value, index) {if (iterator(value, index)) {results.push(value);}}); return results; } function (object) { if (Object.isFunction(this.indexOf)) { if (this.indexOf(object) != -1) { return true; } } var found = false; this.each(function (value) {if (value == object) {found = true;throw $break;}}); return found; } function () { return this.map(); } function reverse() { [native code] } function forEach() { [native code] } function () { this.length = 0; return this; } function () { return this[0]; } function () { return this[this.length - 1]; } function () { return this.select(function (value) {return value != null;}); } function () { return this.inject([], function (array, value) {return array.concat(Object.isArray(value) ? value.flatten() : [value]);}); } function () { var values = $A(arguments); return this.select(function (value) {return !values.include(value);}); } function (sorted) { return this.inject([], function (array, value, index) {if (0 == index || (sorted ? array.last() != value : !array.include(value))) {array.push(value);}return array;}); } function (array) { return this.uniq().findAll(function (item) {return array.detect(function (value) {return item === value;});}); } function () { return [].concat(this); } function () { var results = []; this.each(function (object) {var value = Object.toJSON(object);if (!Object.isUndefined(value)) {results.push(value);}}); return "[" + results.join(", ") + "]"; } As you can see, it shows the 6 elements in the array that I want, but it also shows random elements. By the way, I can fix this by changing it to a normal for loop, but I want to know what I'm doing wrong. Hi I wanted to create multiple check box and once check box is clicked user should able to enter text and submit so i created this but when check box toggle it keep creating text areas. i wanted to create 1 text area per one check box also i need to store each text area value to data base. how can i correct this to achieve my needs PHP Code: <script type="text/javascript"> function validate(chk){ if (chk.checked == 1){ var htmlText = "<textarea name='area' cols='40' rows='5'></textarea>"; var newElement = document.createElement('div'); newElement.id = 'text'; newElement.innerHTML = htmlText; var fieldsArea = document.getElementById('text'); fieldsArea.appendChild(newElement); }else {} } </script> <form> <label>option1 <input type=checkbox name=chk1 onclick="return validate(chk1);"></label> <label>option2 <input type=checkbox name=chk2 onclick="return validate(chk2);"></label> </form> <div id="text"></div> Sorry for the language errors Regards. I tried the following code based on a post I saw somewhere else about summing all the elements of an array together. When I tried it though I couldn't seem to get it working. Can someone please point out what I did wrong or tell me a different way to sum array elements together? Thanks. Code: <script type="text/javascript"> Array.prototype.sum = function() { for (var i = 0, L = this.length, sum = 0; i < L; sum += this[i++]); return sum; } var myArray=[1,2,3,4,5]; document.write(myArray.prototype.sum); </script> Hi all, iv'e been trying to get round this for 2 days and still nothing. What i want to do is to be able to outline elements on a page when hovered over... simple you might think. which it is. Then with the id of the item outlined when right clicked, and chose an option, other things happen. The menu side is sorted, and the hover outline is sorted. But iv'e been trying to put them both together but it wont work! This is the closest iv'e gotten, whcih runs sooooo slow. Code: $(document).ready(function() { function elementHover(){ $("*").bind("mouseover", function(event) { var element = $(event.target); if($(element).attr("rel")!="rightClickMenu"){ $(element).addClass('outline-element'); if( ($(element).attr("id")!="") && (typeof $(element).attr("id") != "undefined") ){ getElementObj($(element)); $("[id!='" + $(element).attr("id") + "']").hover(function(){ $("#" + $(element).attr("id")).removeClass('outline-element'); }); }else{ return ""; } }else{ return ""; } }); } elementHover(); }); the big problem being this var element = $(event.target); if i changed it to var element = $(event.target); alert($(element).attr("id")); it would open the dialog box about 10 times spitting all kinds of results. Any help would be much appreciated. Hi again!! This is my code to add and delete dynamic rows and auto calculate the amount field by multiplying qty and rate. PHP Code: <form name="staff_reg" action="<?php echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']; ?>" method="post" enctype="multipart/form-data"> <table width="100%" border="0" cellspacing="0" cellpadding="2"> <table border="0" cellpadding="1" cellspacing="0" class="normal-text" align="left"> <tr align="center"> <td width="10" class="forhead" style="white-space:nowrap;"> </td> <td width="92" class="forhead" style="white-space:nowrap;">Qty</td> <td width="94" class="forhead" style="white-space:nowrap;">Rate</td> <td width="94" class="forhead" style="white-space:nowrap;">Amount</td> </tr> </table> <tr align="left"> <td class="forhead" style="white-space:nowrap;"><input type="button" value="Add Row" onClick="addRow('dataTable')" > <input type="button" value="Delete Row" onclick="deleteRow('dataTable')" ></td> <table border="0" id="dataTable" cellpadding="1" cellspacing="0" class="normal-text"> <tr> <td width="10" class="forhead" style="white-space:nowrap;"><input type="checkbox" name="chk[]"/></td> <td width="92" class="forhead" style="white-space:nowrap;"> <input type="text" name="qty[]" style="width:80px;" onblur=""> </td> <td width="94" class="forhead" style="white-space:nowrap;"> <input type="text" name="rate[]" style="width:80px;" value=""></td> <td width="94" class="forhead" style="white-space:nowrap;"> <input type="text" onblur="getValues('qty[]','rate[]','amt[]')" name="amt[]" style="width:80px;"></td> </tr> </table> <table border="0"> <tr> <td>Total:</td> <td><input type="text" name="total[]" style="width:80px;" value=""></td> </tr> <tr> <td colspan="2"> <input name="Submit" type="submit" value="Save" style="text-decoration:none" /> <input type="reset" value="Cancel" onclick="window.location.href='<?php echo $_SERVER['PHP_SELF'];?>'"> </td> </tr> </form> <script type="text/javascript"> function getValues(objName,objName2,objName3) { var var3 = ""; var arr = new Array(); arr = document.getElementsByName(objName); arr2 = document.getElementsByName(objName2); arr3 = document.getElementsByName(objName3); for(var i = 0; i < arr.length; i++) { for(var i = 0; i < arr2.length; i++) { for(var i = 0; i < arr3.length; i++) { var obj1 = document.getElementsByName(objName2).item(i); var var2 = obj1.value; var obj = document.getElementsByName(objName).item(i); var var1 = obj.value; var obj3 = document.getElementsByName(objName3).item(i); var var3 = obj3.value; var var4 = var1 * var2; document.getElementsByName(objName3).item(i).value=var4; } } } } function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var colCount = table.rows[0].cells.length; for(var i=0; i<colCount; i++) { var newcell = row.insertCell(i); newcell.innerHTML = table.rows[0].cells[i].innerHTML; //alert(newcell.childNodes); switch(newcell.childNodes[0].type) { case "text": newcell.childNodes[0].value = ""; break; case "checkbox": newcell.childNodes[0].checked = false; break; case "select-one": newcell.childNodes[0].selectedIndex = 0; break; } } } function deleteRow(tableID) { try { var table = document.getElementById(tableID); var rowCount = table.rows.length; for(var i=0; i<rowCount; i++) { var row = table.rows[i]; var chkbox = row.cells[0].childNodes[0]; if (null != chkbox && true == chkbox.checked) { if (rowCount <= 1) { alert("Cannot delete all the rows."); break; } table.deleteRow(i); rowCount--; i--; } } } catch(e) { alert(e); } } </script> I would like to know that how can I show the value of all the elements in array "amount" in total field?? |