JavaScript - Loop Through Gridview?
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 Similar TutorialsHi all, Does anybody know how to get the rownumber from a gridview on mouseover. The gridview is on an aspx page and i need to call the javascript from the rowcreated part. I am still a newbie to javascript, so any help is a lot of help. Thank you hi guys i hava gridview gvcustomers with following fields latitude,longitude,customer and i have a javascript function in my aspx page fucntion Customer() { AddCustomer(lat1,long1)--- row1 of gridview lat long AddCustomer(lat2,long2)--row2 of gridview lat long } in the above function i would like to loop through the gridview and get the latitude and longitude colmns in the function instead of hardcoding as i have been doing now...thank you i advance Hi, I am new to javascript and need help to get the value from af gridview cell and write it to an asp.net control on my aspx page ( language Visual Basic ). I have a gridview ( gridview1) which contains some numbers in the first column. I need to get the number in the column on mouseover and write to an asp.net label, textbox or hiddenfield. I know how to activate the script from from my aspx page, but I havent got a clue on how to write the script. Any help is deeply appreciated. I want to change the color of the gridview when a button which has the value of the row index of the gridview is clicked ...this button is not inside the gridview but some where else on the form but it can send the gridview rowindex to the function so need a function to change the color of the row or bring it to focus in someway... 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 } } 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? 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> 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 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 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 = ''; } } 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 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 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! I have a dice rolling function. The user enters the number of sides, and the dice rolls 36000 times. I track the results, and then display the percentages of each number being rolled as well. I have it to where it displays but only for ONE die ( eg : a 5 sided die, it only displays up to 5, and not 10 ) But the function is rolling for both die, just not displaying. I'm thinking I need to change, in the rollDice function, <=d.side to <=rolled_value, but whenever I do this, I get NaN errors. Any help would be appreciated! Code: <script type="text/javascript"> function Die(side) { this.side = side; this.roll = function () { var result; result = parseInt(((Math.random() * 1000) % this.side) + 1 ); return result; } // <![CDATA[ this.validateNum = function (side) { if (side > 1 && side < 101) return true; else return false; } } function rollDice() { var d = new Die(document.getElementById('number').value); if (d.validateNum(d.side) == true) { var numCount = new Array(d.side); var percent; var rolled_value; for (var i=1; i<=d.side; i++) numCount[i] = 0; for (var j=0; j<36000; j++) { rolled_value = d.roll() + d.roll(); numCount[rolled_value] = numCount[rolled_value] + 1; } for (var k=1; k <= d.side; k++) document.writeln("Number of" + " " + k +"'s" + " " + "rolled" + ' : ' + numCount[k] + '<br/>' ); for (var l = 1; l <= d.side; l++) { percent = new Number(parseFloat(numCount[l] / 36000) * 100).toFixed(2); document.writeln("Percentage of" + " " + l + " " + "being rolled" + ' : ' + percent + '% <br/>'); } } //]]> Hi All, could you please help me. A have a little program and i need to count somehow how many times a while loop is ran. how could i do that? Thanks for your help Trying to use a "for" loop to cycle through an array and compare values; if the values are equal, then it displays a message about the team, etc. Code: <html> <head> <title>Javascript Colors!</title> <script type="text/javascript"> var teamcolors = ["blue","orange","Auburn Tigers","Yuck!","black","red","Georgia Bulldogs","Congratulations!","yellow","black","Georgia Tech","Awesome!"] function changeBGColor() { document.body.bgColor = prompt("What color should the background be?","Put ANY color here!"); checkForTeamColors(); } function changeTXTColor() { document.getElementById("text").style.color = prompt("What color should the text be?","Put ANY color here!"); checkForTeamColors(); } function checkForTeamColors() { var bgcolor = document.body.bgColor var txtcolor = document.getElementById("text").style.color var loopcount = 1 while (loopcount <= 12) { if ( (bgcolor == teamcolors[loopcount] && txtcolor == teamcolors[loopcount + 1]) || (bgcolor == teamcolors[loopcount + 1] && txtcolor == teamcolors[loopcount]) ) { alert("You have picked the team colors of " + teamcolors[loopcount + 2] + ". " + taemcolors[loopcount+3]) } loopcount = loopcount + 4; } } </script> </head> <body> <p id="text" align="center">This text will change color if you want to. <br> Maybe try a certain combination, like Orange and Blue, or Red and Black?<br></p> <button onClick="changeBGColor()">Click me to change the BG Color!</button> <button onclick="changeTXTColor()">Click me to change the text Color!</button> <p id="variables"></p> <script type="text/javascript" document.getElementById("variables").innerHTML = ( bgcolor + " " + txtcolor ) </body> </html> So this is what I have so far: Code: import java.util.Random; public class lotteryGame { public static void main(String args[]) throws Exception { int n=0; // counter for the amount of times played int t=0; // total amount of winnings int i=0; // number of matches int a; // first guess int b; // second guess int c; // third guess int d; // first number in the lottery int e; // second number in the lottery int f; // third number in the lottery Random rand = new Random(); while (n<100) // play the game for 100 times { a=rand.nextInt(9) + 1; // assign a random number to a b=rand.nextInt(9) + 1; c=rand.nextInt(9) + 1; System.out.println("Lottery Number"+a+b+c); d=rand.nextInt(9) + 1; e=rand.nextInt(9) + 1; f=rand.nextInt(9) + 1; System.out.println("Your guess"+d+e+f); if (a==d){ i=i+1; System.out.println(a+"is a match"); d=d+10; // if a=d then d is taken out of the range (1-9) } else if (a==e){ System.out.println(a+"is a match"); i=i+1; e=e+10; } else if (a==f){ System.out.println(a+"is a match"); i=i+1; f=f+10; } if (b==d){ System.out.println(b+"is a match"); i=i+1; d=d+10; } else if (b==e){ System.out.println(b+"is a match"); i=i+1; e=e+10; } else if (b==f){ System.out.println(b+"is a match"); i=i+1; f=f+10; } if (c==d){ System.out.println(c+"is a match"); i=i+1; d=d+10; } else if (c==e){ System.out.println(c+"is a match"); i=i+1; e=e+10; } else if (c==f){ System.out.println(c+"is a match"); i=i+1; f=f+10; } if (i==3){ if (a==d-10&&b==e-10&&c==f-10){ t=t+10000; System.out.println("You win!!!"); } else{ t=t+1000; System.out.println("You had 3 matches! You win $1000"); } } if (i==2){ t=t+50; System.out.println("You had 2 matches! You win $50"); } if (i==1){ t=t+10; System.out.println("You had 1 match! You win $10"); } } n=n+1; i=0; } } I don't know what is wrong with the program, It compiles fine but when I run it, it never stops. =/ I figure that Code: n=n+1 would be a counter to stop the while loop. Where do I place it so it can count everytime it runs. Or, What do I need to add in order for the program to stop running after 100 times? Thank You. =] |