JavaScript - Issue With Script (loops And Arrays)
I am having an issue with this script I wrote. Actually it works the way it is now, but not the way I want it too.
This is a random raffle ticket number generater. The guys at the fire department where talking about selling 300 tickets and discussing how they were going to select and call the numbers. It got me thinking and inspired to start messing around with javascript again. It all starts with index.html and a form w/ a button and textarea. When a user clicks the button it will generate a random number and insert it into the textarea. This is accomplished by the Generate(); function that is in Genny.js an external js file. Code: <h2>Raffle Ticket Number Generator</h2> <form name="theform"> <input type="button" name="pickNumber" value="Pick a Winner" onclick="Generate();" /> <br /><br /> <textarea cols="40" rows="25" name="winnersCircle">Winning Numbers Will Display Here! </textarea> </form> This much works just fine. Now onto Genny.js Code: //initialize counter and array count = 1; winners = new Array(); function Generate(){ //generate a random number from 0-300 var random_number = Math.floor(Math.random()*301); //checks output of Math.random() against winners array to see if number has been used already for (i = 0; i < winners.length; i++ ) { if ( winners[i] == random_number ) alert("I am so sorry... we have accidently drawn a duplicate number! Please pick again."); } //add the number to the array winners[count] = random_number; //increment the counter count++; //display the stored random number document.theform.winnersCircle.value = winners.join("\n"); } This much works...somewhat! It generates the random number and checks the winners array to see if it is already used. If it wasn't used it adds the number to the array, increments the counter, and then displays the number in the textarea of the form, as it should. If the number was used it alerts the user, once the user clicks the button to accept the alert it carries on with the script and adds it to the array again and also displays it. This is not what I want it to do. If the number was used I do not want it added to the array or displayed. I would also like it to regenerate another number without the alert. The alert was wrote in to assist me in checking to see if it was finding a duplicate number, thats all. As an extra, is there a way to also add a numbered list to the results. To show the sequence of the ticket draw. I have messed with this for days and rewrote it over and over. I have used different loops and conditional operators to try and solve this problem. But to no avail. Here I am, asking not for the answer but a push in the right direction. Any help would be great, this is becoming an obsession trying to make it work. The code above is the last attempt at this point. Everything else has returned no values or just errors. Thanks in advance! Similar TutorialsI am working on making 2 for loops of 2 arrays to get the total of them. Then I need to get the average heights. This is for a test, yet I have not got a clue, so I need clues as I cant get it to work and I am a new coder to javascript. Code: var heights = [15,16,17,18,19]; var numbers = [2,1,6,4,2]; var average = new Array(5); average = 0 for (var heights = 0; heights <= 5; heights = heights+ 1) { total = 0 } for (var numbers = 0; numbers <= 5; numbers = numbers + 1) { total = 0 average = heights / numbers; } document.write('The average height is ' + average); Am I on the right road? I need to use this format and not functions. I have got 2 for statements but maybe I could do this with one, it is so tricky this javascript. I am looking to get a loop which runs through a series of divs (each with an attribute called "position" followed by 5 comma separated values). for each of these divs i need the 5 comma separated values (from position) to be assigned to variables. I have the rest of the code sorted out i just cannot get the original variables. Examples: divs look like this... Code: <div position="100,100,50,50,1"></div> There are no limits on the number of these divs but there will never be 0. What i want is something to look like this. For each div, var s = string of attribute (position) values (output:a,b,c,d,e) split string to create var a = a var b = b var c = c var d = d var e = e I from those 5 vars can do what i need. and i know that vars a,b,c,d,e,s will all be overwritten in when it comes to the next div... that is planned. How does my array look so far? thanks I think so what i was supposed to do was insert a script element that contains the function amountTotal() then add commands to the function such as 1 declare variable named total, set intial value to 0 2 create a FOR LOOP that loops all values in amount array. add current value of array item to value of total variable 3 when completed return value of total variable This is what I came up with tell me if this makes sense Thanks Quote: title>The Lighthouse</title> <link href="lhouse.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="list.js"></script> <script type="text/javascript"> function amountTotal() { totalAmount=0; for(var i=0; i<amountTotal.length; i++){ total+=amount(i); { return total; } </script> </head> Does this seem right or is my format all wrong? if so what should i have instead? thanks Hello everyone I am having trouble with a project i am supposed to be doing which is to turn structured English into coding joined with the code i am about to post !! This is the code i have written so far that works: var contestantNamesArray = ['Tom and Nazia', 'Pat and Dan', 'Sandra and Kofi', 'Ian and Adele', 'Paul and Costas']; var judgesPointsArray = [2,1,5,4,3]; var audiencePointsArray = [4,5,2,3,1]; var combinedPointsArray = new Array (5) for (var couple = 0; couple < combinedPointsArray.length; couple = couple + 1) { combinedPointsArray[couple] = judgesPointsArray[couple] + audiencePointsArray[couple]; } var maxCombinedPoints = 0; for (var couple = 0; couple < combinedPointsArray.length; couple = couple + 1) { if (combinedPointsArray[couple] > combinedPointsArray[maxCombinedPoints]) { maxCombinedPoints = couple; } } document.write('The maximum number of points was ' + combinedPointsArray[maxCombinedPoints] + '<BR>'); document.write('The couple(s) scoring the maximum were' + ':' + '<BR>'); Now with that code there i have just posted, I am supposed to take this structured English below and combine them together but cannot work out how to link or code it to get it to work. write out a heading for the list of couples scoring the maximum declare a variable to keep count of how many couples scored the maximum value and initialise it to zero for each couple if this couple scored the maximum write out the couple's names increase the count of couples who scored the maximum value end if if a dance-off is required write out that a dance-off is required else write out that a dance-off is not required end if end for I have tried myself but i am stuck at how to link the contestantNamesArray with the rest of the code in order to be able to display the couples who scored the maximum points and store it in a new variable and then write out the names. Sorry if i have posted wrongly this is my first time and i am a new learner to JavaScript trying to learn basics. Thank you anyone in advance and if you need any further information i will provide anything you need. Gary I've now got to form an average of snowfall inputs, taken from looped prompts, however I'm not allowed to use arrays or functions... Almost every example I see uses arrays, such as this one he http://www.codingforums.com/showthread.php?t=4313 Is it possible to not use arrays to form the average? Please describe how to do this in general terms, as was highlighted in that link ^^^ I want to learn, not copy, although one can be derived from the other... What I haveso far, assume all vars have been announced. Code: for (var d=1; d<=numofinputs; d=d+1) { input = prompt("Enter a data input" + d) } Is it possible I'm attempting this in too general a manner? ie, running before I can walk. 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; Hello everyone, I have been working on this function but no luck so far. Basically this is a simple vertical navigation menu, and I am just trying to to show or hide the sub-menus (unordered lists) with onmouseover & onmouseout. I can do this very easily with just css or inline events, but I'm just trying to figure it out the way I already set it up. So I am looping through the ULs first, then I loop through the LIs. Furthermore I find the right LI elements by checking their class names, and if they exist I trigger the onmouseover & onmouseout events on them so the ULs will appear/disappear. The issue is that this works only for the last list item because I am guessing of a closure. So instead of getting each item individually at each event, instead it gives me the last list item. I have searched the web for a while now about closures and such, but all the examples I find talk about nested functions and a single loop, which isn't my case because I have two loops and only one function. Any help would be appreciated. HTML Code: Code: <div id="navWrapper"> <ul> <li class="triggers"><a href="#">Item 1</a> <ul class="subMenu"> <li><a href="#">Item 1.1</a></li> <li><a href="#">Item 1.2</a></li> <li><a href="#">Item 1.3</a></li> </ul> </li> <li class="triggers"><a href="#">Item 2</a> <ul class="subMenu"> <li><a href="#">Item 2.1</a></li> <li><a href="#">Item 2.2</a></li> <li><a href="#">Item 2.3</a></li> </ul> </li> <li class="triggers"><a href="#">Item 3</a> <ul class="subMenu"> <li><a href="#">Item 3.1</a></li> <li><a href="#">Item 3.2</a></li> <li><a href="#">Item 3.3</a></li> </ul> </li> </ul> </div> Javascript Code: Code: <script type="text/javascript"> function hoverSh () { var navWrap = document.getElementById('navWrapper'); var uls = navWrap.getElementsByTagName('ul'); var listItems = navWrap.getElementsByTagName('li'); for (var i=0; i<uls.length; i++) { if (uls[i].className == "subMenu") { var theUls = uls[i]; for (var j=0, c=listItems.length; j<c; j++) { if (listItems[j].className == "triggers") { var theItems = listItems[j]; theItems.onmouseover = function () {//alert(this.nodeName + i);return false; theUls.style.display = 'block'; } theItems.onmouseout = function () { theUls.style.display = 'none'; } }//end inner if }//end inner loop w/ j }//end if }//end outer loop w/ i } window.onload = hoverSh; </script> Any links pointing to simplified tutorials on closures would be helpful too. I thought I understood them but I guess not! I need help placing this code in a table that is one column wide by 20 rows long. <!DOCTYPE html> <html> <head> <title>Table</title> <meta charset="UTF-8" /> <table cellspacing="5" border="2"> <script> document.write("<h2>Table of Fibonacci Numbers</h2>"); for (i=0, j=1, k=0, fib =0; i<15; i++, fib=j+k, j=k, k=fib){ document.write("Fibonacci (" + i + ") = " + fib); document.write("<br>"); } </script> </table> </html> I know this maybe sounds "newbie", perhaps I am still one. I have 3 divs, all of them in a group "name", there are h1 tags inside them with names too. Well actually I have many many divs like this in several pages so I must use a JS sheet (.js). Code: <div name="area"> <h1 name="stringRed"> Mercury </h1> </div> <div name="area"> <h1 name="stringRed"> Venus </h1> </div> <div name="area"> <h1 name="stringRed"> Earth </h1> </div> The idea is to create an event for the divs, a mouseover event to a div in order to change the color of the words inside the h1 tags. When the mouse is over one particular div the word inside it must change to red. I was trying this Java Script script: (a cross-browser event handler present) Code: function initialize ( ) { aArea=document.getElementsByName("area"); aStringRed=document.getElementsByName("stringRed"); for (var i=0; i < aArea.length; i++) { addEvent (aArea[i], 'mouseover', changeColor); addEvent (aArea[i], 'mouseout', changeOutColor); } } function changeColor() { ???? } function changeOutColor() { ???? } Thank you in advanced for any help. Hi, I'm new to JS and I am trying to build my first script. My problem, is I'm trying to build a multi hide/show script, displaying paragraphs of information. If I want multiple variables for the script do I have to use an array? and if so, how can I construct this array? Here is my script as of now, <!-- // this tells jquery to run the function below once the DOM is read $(document).ready(function() { // choose text for the show/hide link var showText="Resume"; var hideText="Hide"; var profile_showText="Profile"; var profile_hideText="Hide"; // append show/hide links to the element directly preceding the element with a class of "toggle" $(".toggle").prev().append(' (<a href="#" class="toggleLink">'+showText+'</a>)'); $(".profile_toggle").prev().append(' (<a href="#" class="profile_toggleLink">'+profile_showText+'</a>)'); // hide all of the elements with a class of 'toggle' $('.toggle').hide(); $('.profile_toggle').hide(); // capture clicks on the toggle links $('a.toggleLink').click(function() { $('a.profile_toggleLink').click(function() { // change the link depending on whether the element is shown or hidden if ($(this).html()==showText) { $(this).html(hideText); } else { $(this).html(showText); } // profile_toggle if ($(this).html()==profile_showText) { $(this).html(profile_hideText); } else { $(this).html(profile_showText); } // toggle the display $(this).parent().next('.toggle').toggle('fast'); // profile_toggle $(this).parent().next('.profile_toggle').profile_toggle('fast'); // return false so any link destination is not followed return false; }); }); }); //--> Right now the script doesn't work with the bottom two variables profile_"ect." Please help, been working on this for sometime and its probably an easy fix for someone experienced. Thanks! I need to loop the alphabet and numbers 0-9 to initialize a few thousand arrays. This is for my site and is truly needed. http://www.thefreemenu.com I currently have every array written out and it takes up to much space in my .js file. The majority of my variables are empty but necessary and need to be there (including empty) for my site to work properly. Question is the last part Here's where I'm at. Code: var NewVarLetterOrNum = "a"; eval("_oneofseveralnames_" + NewVarLetterOrNum + "='this part works';"); alert(_oneofseveralnames_a); This creates the variable _oneofseveralnames_a='this part works' Code: var newArrayLetterOrNum = "a"; eval("_oneofseveralnames_" + newArrayLetterOrNum + "= new Array();"); alert(_oneofseveralnames_a) This creates the Array _oneofseveralnames_a=new Array(); and all the values in the array are null, but, now a variable like _nl_a[1]='something' can be used elsewhere because the array exists. This is all that is necessary for now because I can probably set all the variables to be blank with something like Code: i=1 while(i<=20){ _oneofseveralnames_a[i]="1-20"; i++ } alert(_oneofseveralnames_[20]); So now you have what I came to understand in the first few hours. Now to the hard part : ( I can't make multiple array's dynamically. I dont' know if its because I don't understand loops or arrays or what and its very fustrating. As for any answer you might be so kind as to provide, if you could dumb it down that would be greatly appreciated. Code: var newArray =new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z') i=1 while(i<=26){ eval("_nl_" + newArray[i] + "= new Array();"); i++ } alert(newArray[1]) // Is b, but alert(_nl_b) //I can't get _nl_b to exist, I tried everything including taking away the quotes around the letters in every test */ var _nl_a =new Array() var _img_a =new Array() var _h_a =new Array() var _r_a =new Array() var _m_a =new Array() var _yt_a =new Array() var _i_a =new Array() The above arrays are all the array _name_ parts I need but for example, a has 10 parts, a,p2_a,p3_a,.. p10_a. I need 10 pages for each letter of the alphabet and numbers 0-9 and a special all1, p2_all1 ... p10_all1. Overall 2200 arrays that need to be declared. Currently they are all written out. /* I'm trying to resize this to about 60% smaller... it's a live chat pop-up, but out of my realm to expertise... can anyone help? It's the pop-up on the website brandedgear.com after about 25 seconds. Thanks! <div style="FLOAT: left; WIDTH: 500px; BACKGROUND: #FFFFFF url(<{$_themePath}>images/mainbackground.gif) REPEAT; BORDER: SOLID 1px #bcb5a6;"> <div style="BACKGROUND: #FFFFFF url(<{$_themePath}>images/icon_proactiveuserbackground.gif) NO-REPEAT bottom left; BORDER: SOLID 1px #bcb5a6; MARGIN: 8px;"> <div style="TEXT-ALIGN: center;"><img src="<{$_themePath}>images/<{$_product}>.gif" border="0" align="absmiddle" /></div> <HR align="center" style="WIDTH: 80%; BORDER: none; COLOR: #bcb5a6; BACKGROUND-COLOR: #bcb5a6; HEIGHT: 1px; MARGIN-TOP: 10px; MARGIN-BOTTOM: 3px;" /> <div style="PADDING-LEFT: 120px; TEXT-ALIGN: left; MARGIN-TOP: 30px; HEIGHT: 80px; FONT: 45px Trebuchet MS, Georgia, Verdana, Arial, Helvetica; COLOR: #333333;"> <{$_language[proactivetitle]}> </div> <div style="PADDING-LEFT: 120px; VERTICAL-ALIGN: top; MARGIN-TOP: 0px; PADDING-TOP: 0px; HEIGHT: 200px; FONT: 18pt Trebuchet MS, Georgia, Verdana, Arial, Helvetica; COLOR: #776849;"> <{$_language[proactivemsg]}><br /> <div style="PADDING-TOP: 30px; PADDING-LEFT: 80px; TEXT-ALIGN: center;"><div style="BORDER: SOLID 0 #FFFFFF; TEXT-ALIGN: center; BACKGROUND: URL(<{$_themePath}>images/proactivebutton.gif) no-repeat; HEIGHT: 37px; WIDTH: 135px; COLOR: #000000; FONT-WEIGHT: bold; FONT-FAMILY: Trebuchet MS, Georgia, Helvetica, Verdana, Tahoma; FONT-SIZE: 16px; MARGIN: 0px; PADDING-TOP: 6px; PADDING-BOTTOM: 15px; VERTICAL-ALIGN: middle; CURSOR: pointer;" onmouseover="this.style.color='red';" onmouseout="this.style.color='#000000'" onclick="javascript:doProactiveRequest_<{$_randomSuffix}>();"><{$_language[proactivechatnow]}></div></div> </div> </div> </div><div style="FLOAT: left; MARGIN-LEFT: -8px; MARGIN-TOP: -8px;"><a href="javascript:closeProactiveRequest_<{$_randomSuffix}>();"><img src="<{$_themePath}>images/icon_close.png" border="0" align="absmiddle" /></a></div> 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 Everyone! I'm new to JavaScript. I thought of learning by doing instead of just reading tutorials and books. So I started writing a Greasemonkey script for Facebook. Basically what it does is it creates a link to download photo albums from Facebook. I'm far from finished but anyway, here's my code so far. The format of the HTML code block where the URLs of pics are. Code: <div class="tagWrapper"> <i style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/299595_10150290138650735_543370734_8021370_355110168_a.jpg);"></i> </div> And here's my script so far, Code: var picURL; var modURL; var URLset = []; for(var i=0; i<picURL.length; i++) { //gets all the URLs in the page picURL = document.getElementsByClassName("tagWrapper")[0].children[0].style.backgroundImage; modifyURL(picURL); URLset.push(modURL); //inserting them to an array alert(URLset) ; } function modifyURL(); { //doing the replacements to make them downloadable modURL = picURL.replace("url(", "").replace(")", ""); modURL = modURL.replace("a.jpg", "n.jpg"); var dwn = "?dl=1"; modURL = modURL.concat(dwn); return modURL; } I have created a fiddle so that it all would be clearer. Since I'm half way through it, I just want to make sure it works up to this point so I have put an alert box to show all the modified URLs stored in the array. (supposed to, at least) the problem is, it isn't showing up. Can anyone please tell me what I have done wrong here? Bare with me for I'm new to this as I've mentioned earlier. Any help in teh right direction would be much appreciated. Thanks in advance. Hey there! This code I am posting is used for some tests I'm doing with PHP and AJAX. What I find absolutely confusing is that when I add the refreshDir() function to any of the other functions, so that it runs once they have done their buisness, it absolutely screws up what-ever function I have it in. For instance if I have it running in the deleteTheFile() function. It prevents it from deleting the file. That function works perfectly fine when the refreshDir() function is not in it. Any hints or solutions? Please let me know if you'd like to see any of my other code. I'm posting the page's code along with the JS file and the Delete the file php page that deletes the files (there are other php files that create and read files). This whole thing was meant to be a simple exercise, but I am entirely confused as to why the refeshDir() function is screwing up everything. I don't think that the issue is related to anything else other than the javascript / ajax. Thanks for your help! Here is the JS file: Code: if (window.XMLHttpRequest){ ajaxRequest=new XMLHttpRequest(); } else{ alert('Try again gold star!'); } var createResponse = 'Created Successfully'; var deleteResponse = 'Deleted Successfully'; var i = 0; function refreshDir(){ ajaxRequest.onreadystatechange = function(){ if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200){ document.getElementById('directory').innerHTML = ajaxRequest.responseText; } } ajaxRequest.open('GET', 'theReadDir.php', true); ajaxRequest.send(); } function createTheFile(file){ var file = document.getElementById(file).value; var textInput = document.getElementById('toBeInserted').value; ajaxRequest.onreadystatechange=function(){ if (ajaxRequest.readyState==4 && ajaxRequest.status==200){ document.getElementById('responseCreated').innerHTML = " " + createResponse; } } ajaxRequest.open("POST", "theCreator.php", true); ajaxRequest.setRequestHeader('Content-type','application/x-www-form-urlencoded'); ajaxRequest.send("inserted=" + textInput + '&file=' + file); // refreshDir(); } function readTheFile(file){ var file = document.getElementById(file).innerHTML; ajaxRequest.onreadystatechange=function(){ if (ajaxRequest.readyState==4 && ajaxRequest.status==200){ document.getElementById('responseRead').innerHTML = ajaxRequest.responseText; } } ajaxRequest.open('GET', 'theReader.php?file=' + file, true); ajaxRequest.send(); } function readTheFileEntered(file){ var file = document.getElementById(file).value; ajaxRequest.onreadystatechange = function(){ if (ajaxRequest.readyState==4 && ajaxRequest.status==200){ document.getElementById('responseRead').innerHTML = ajaxRequest.responseText; } } ajaxRequest.open('GET', 'theReader.php?file=' + file + '&dir=', true); ajaxRequest.send(); } function deleteTheFile(file){ var file = document.getElementById(file).value; alert(file); ajaxRequest.onreadystatechange = function(){ alert(0); if (ajaxRequest.readyState == 1 && ajaxRequest.status == 200){ alert(1); } if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200){ document.getElementById('responseDeleted').innerHTML = ' ' + deleteResponse; document.getElementById('responseDeleted').innerHTML = ' ' + ajaxRequest.responseText; } } alert(2); ajaxRequest.open('GET', 'theDeleter.php?file=' + file, true); alert(3); ajaxRequest.send(); alert(4); refreshDir(); } function resetFeedback(response){ document.getElementById(response).innerHTML = ''; } /*function removeAlert(){ var t = setTimeout("resetFeedback('responseDeleted')", 2000); } function updateSatus(){ document.getElementById('createButton').innerHTML = 'Update'; i += 1; if (i > 1) createResponse = 'Updated Successfully'; var t = setTimeout("resetFeedback('responseCreated')", 2000); } */ Here is the main page code: Code: <html> <head> <script type="text/javascript" src="operations.js"></script> <style type='text/css'> .niceboy{ font-family: Arial, sans-serif; font-weight: bold; font-size: 13px; color: #fff; text-align: center; text-shadow: 0px 1px 0px #B7B7B7; background-image: -webkit-linear-gradient(top,#D1D1D1,#c9c9c9); border-color: #BABABA; border-style: solid; border-radius: 12px; border-width: 1px; padding-left: 8px; padding-right: 8px; line-height: 24px; display: inline-block; cursor: pointer; } .listing{ margin: 4px; width: 200px; padding-left: 15px; cursor: pointer; } .listingfile{ background-color:#f0f0f0; } .listingdir{ background-color:#e3e3e3; } #directory{ margin: 20px; } </style> </head> <body onLoad="refreshDir();"> File Name: <input type='text' id='file' /> <br /> <br /> File Contents: <input type='text' id='toBeInserted' /> <br /> <br /> <br /> <div class='niceboy' id='createButton' onclick='createTheFile("file");'> Create </div> <span id='responseCreated'></span> <br /> <br /> <div class='niceboy' onclick='readTheFileEntered("file")'> Read </div> <span id="responseRead"></span> <br /> <br /> <div class='niceboy' onclick='deleteTheFile("file");'> Delete </div> <span id = 'responseDeleted'></span> <br /> <br /> <div class='niceboy' onClick='refreshDir();'> Refresh </div> <div id='directory'> </div> <br /> <br /> </html> </body> Here's the theDeleter.php file: PHP Code: <?php $file = $_GET['file']; //$file = 'created-files/'. $file; echo $file; function delete($file){ unlink($file); echo 'Deleted Successfully'; } if (file_exists($file) && is_file($file)) delete($file); else echo 'whoa bro that file doesn\'t exist!'; ?> And here's the theReadDir.php: PHP Code: <?php $dir = new DirectoryIterator('/wamp/www/phpAjaxTest/'); foreach($dir as $file){ if (!$dir->isDot()){ $ft = filetype($file); if ($ft == 'dir'){ $format = '<div class=\'listing listing' . $ft . '\' id = \'' . $file . '\' onClick = "readTheFile(\'' . $file . '\'); refreshDir();">' . $file . '</div>'; echo $format; } else{ $format = '<div class=\'listing listing' . $ft . '\' id = \'' . $file . '\' onClick = "readTheFile(\'' . $file . '\');">' . $file . '</div>'; echo $format; } } } ?> Basically any of the other function's (the only one's that I'd want refreshDir() to run in would be the creating and deleting functions) break when I add the refreshDir() function. I'm admittedly green in this area [among others!], but will there be any issues with any browsers loading the url below with the scripts at the bottom of the page like I have them? http://alton.k12.mo.us/index.html FF loads them fine for me, as does IE *until* I hit the compatibility mode button, then it seems to sort of "hang"...but with IE, I'm not really ever sure of what it's doing is correct or not? This script isnt working. Im not sure what im doing wrong. forgive me i havent programmed in javascript before. titles.js Code: <script type="text/javascript" language="javascript"> <!--// function random_Title(){ if (parseInt(navigator.appVersion) >= 4) { var num = 3; var rantitle = new Array(num+1); rantitle[1] = "Random Title1"; rantitle[2] = "Random Title1"; rantitle[3] = "Random Title1"; ranNumber = parseInt(num * Math.random() + 1); document.title = rantitle[ranNumber]; } //--> } </script> html page Code: <html> <head> <script type='text/javascript' src='http://www.flashmajic.com/Google/titles.js'></script> <script> document.title = random_Title() ; </script> </head hi I am creating a gallery using my flickr feed. I have the bones of it working the only issue is with the thumbnail pulled from flickr. You get the option of small medium and large whicj Im using meduim. I want to add an image border around the thumbnails using a background image but when I add the styles it wont work. If i add a width to the img tag it will distrit the images because its being pulled from the flickr api anyone any ideas on how to get the background image working? html code is here Code: <body> <!-- Some Content --> <div id="gallery"> <input type='hidden' id='current_page' /> <input type='hidden' id='show_per_page' /> <div id="flickr"> </div> <div id='page_navigation'></div> </div> </body> CSS for the img is Code: [.hidden { display: none; } div#flickr a.lightbox img { border: 5px solid #b3aaa4; margin-left: 5px; margin-right: 5px; margin-bottom:30px } and the java script is here Code: $(function() { $.getJSON('http://api.flickr.com/services/rest/?format=json&method='+ 'flickr.photos.search&api_key=' + apiKey + '&user_id=' + userId + '&tags=' + tag + '&per_page=' + perPage + '&jsoncallback=?', function(data){ var classShown = 'class="lightbox"'; var classHidden = 'class="lightbox hidden"'; $.each(data.photos.photo, function(i, rPhoto){ var basePhotoURL = 'http://farm' + rPhoto.farm + '.static.flickr.com/' + rPhoto.server + '/' + rPhoto.id + '_' + rPhoto.secret; var thumbPhotoURL = basePhotoURL + '_m.jpg'; var mediumPhotoURL = basePhotoURL + '.jpg'; var photoStringStart = '<a '; var photoStringEnd = 'title="' + rPhoto.title + '" href="'+ mediumPhotoURL +'"><img src="' + thumbPhotoURL + '" alt="' + rPhoto.title + '"/></a>;' var photoString = (i < showOnPage) ? photoStringStart + classShown + photoStringEnd : photoStringStart + classHidden + photoStringEnd; $(photoString).appendTo("#flickr"); }); $("a.lightbox").lightBox(); }); }); anyone? I tried posting the code but it's too long... Page address: http://professorcuddlecore.com/paintings/ Problem: Click first or second photo, pops up fine, bottom text is behind the photo. You can view the JS by viewing source etc, sorry I can't fit it here. I spent 2-3 hours trying to figure out the problem but I'm new to JS and it looks like pretty convoluted code I'm using (obviously didn't write it myself, it's by "PopBox.") Thanks for any time spent helping me, pre-appreciated. Hi Script Experts I am facing issue in below code for Brisilia time zone.(GMT-3). Issue comes in October month only. It is going tobig loop. I am not getting how Date object is behaving here. Thanks in advance Pranav Sharma *********************************** <script type="text/javascript"> var nDate; var nCurrentYear = 2011; var nCurrentMonth = 10; nYear=2011; nMonth=10; var date = new Date(nYear, nMonth-1, 1); document.write('Month:'+date.getMonth() +':CurrentMonth:'+nCurrentMonth); while (date.getMonth() == nCurrentMonth-1) { nDate = date.getDate(); document.write(date.toDateString()); date = new Date(nCurrentYear, date.getMonth(), date.getDate()+1); } </script> ********************************** |