JavaScript - Asynchronous Ajax Driving Me Crazy. How To Act Upon Response W/o Going Synchronous?
long story short, I have been trying to run a loop, say, 10 times and I know the result I want will be on the first request but it sends all 10 at the same time, over writing the variable for xmlhttp. discovering in my days of attempts that its just the nature of the beast, but I would like ANY way possible to get a response on the 1st pass of the loop in any way possible. But for now, here's a riddle I can't solve, how to make this function return with the response?
Code: function ajaxRequest(query){ var response = 'I have not checked yet.'; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { response = xmlhttp.responseText.trim(); } } xmlhttp.open("GET",query,true); xmlhttp.send(); return response; } It will always instantly say "I have not checked yet." when I would like the response. I'm okay with it being a 2-5 second delay as long as it doesn't pause the browser like a synchronous request. Even a delay of some sort just before the return would probably do it. In that case, I think I can get the rest. Thanks much in advance! Similar Tutorialshi... I'm trying to pass this string and I keep getting the "missing ; before statement error" which I know means I not escaping something or something, but I've tried it every way I can think of and still no dice... any ideas? Code: content='<a href onclick="javascript: document.getElementById('searchbox').style.display='inline'">here<\/a> to enter your address' +'<div id="searchbox" display="hidden"><form action="javascript:getDirections()">' +'<input type="hidden" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +'<div>'; thanks in advance... Hi, I read several examples, tried them all out - and nothing works! Driving me crazy - completely insane! Maybe you guys can help My problem is simple: file B.html includes this line: Code: <script type="text/javascript" src="B.js" defer="defer"></script> file B.js is a regular JS file, yet I need to insert a PHP function in it (yeah - I know it will operate server-side before the page reaches the browser). I did something like: Code: (some js code) var user_id = <?php $a=100; $b=200; $c=$a+$b; echo($c);?>; alert("Your user ID is:" + user_id); (some more js code) (What I expect is the browser to see the line as: var user_id = 300; ) Doesn't work. Renaming B.js to B.php did nothing. What am I doing wrong? Thanks! This has been driving me crazy all day, cant seem to work out what im doing wrong. Alerts the correct URL Used document.write and it works But the redirect command doesnt initiate automatically on click and im not sure why. Someone help!! Code: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>http</title> <style> <!-- p.MsoNormal {mso-style-parent:""; margin-bottom:.0001pt; font-size:11.0pt; font-family:"Calibri","sans-serif"; margin-left:0cm; margin-right:0cm; margin-top:0cm} --> </style> <script type="text/javascript"> function buildstring(form) { var text = form.text.value; var xmljson = form.choice1.value; var init = 'localhost:1234/PPTX/tr?service=extract&action=extractAll&text='; var op = '&op='; var first = init + text + op + xmljson; var complete = "http://" + first; alert (complete); window.location = complete; } </script> </head> <body> <form method="get" id="urlbuild"> <table> <tr> <td> <h2>URL Builder</h2> </td> </tr> <tr> <td> <input type="text" size="100" name="text" value=""> </td> </tr> </table> <table> <tr> <td> <select type="one" name="choice1"> <option value="xml"> XML </option> <option value="json"> JSON </option> </select> </td> <td> <p>Please choose XML or JSON.</p> </td> </tr> </table> <table> <tr> <td> <input type="submit" onClick="buildstring(this.form)"> </td> </tr> </table> </form> </body> </html> i have a drop down which triggers a ajax call. The ajax response is a form with various fields depending upon the drop down option selected. I have a text field in that response form which is to input the date. i have a calender widget and wish to display that as a popup with an onfocus or onclick on that text field. But becoz of the ajax response it does not let me do it. I know the problem is in the creation and destruction of the element where the calender has to be displayed so i tried putting the callender intiialization function in another function and calling that onclick but id doesnt work. below is my modified javascript code for the initialization of the calendar. Code: <script type="text/javascript"> var calendar1, calendar2, calendar3; /*must be declared in global scope*/ /*put the calendar initializations in the window's onload() method*/ function cal_init() { alert("hi"); calendar1 = new Epoch('cal1','popup',document.getElementById('calendar1_container'),false); calendar2 = new Epoch('cal1','popup',document.getElementById('calendar2_container'),false); calendar3 = new Epoch('cal1','popup',document.getElementById('calendar3_container'),false); }; </script> I'm make a ajax call to a processing PHP file that echos either "success" or an "error message". When the success is returning, i want Jquery to recognize this and then redirect the browsers instead of displaying the success message. Here are some snippets. I can only seem to parse to a blank or null. Jquery code: Code: $.ajax({ type: "POST", url: "process.php", data: wfLoginPost(), success: function(msg){ alert(msg); // both below are either null or blank //var res = $(msg).find("span.response").text(); //var res = $(msg).find("span.response").html(); if(res == 'Success'){ window.location = 'http://www.google.com'; } } }); process.php PHP Code: if($qry[0]['pwd'] == $password){ echo "<span class='response'>Success</span>"; }else{ echo "<span class='response'>Username or password did not match</span>"; } Here is the contents of the msg response from the ajax post: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" type="text/css" href="css/reset.css"/> <link rel="stylesheet" type="text/css" href="css/960grid.css"/> <link rel="stylesheet" type="text/css" href="css/style.css"/> <link rel="stylesheet" type="text/css" href="css/statusmessageQ.css"/> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.statusmessageQ-0.5.js"></script> </head> <span class='response'>Success</span> Hi all I am creating a shopping cart in HTML & JavaScript. It's very nearly complete but I've hit a brick wall with trying to delete a single item. Where I list the shopping cart I have a delete button by every item. Here is the code to show that: Code: var buttonnode3= document.createElement('input'); // Create a button for each item to delete buttonnode3.setAttribute('type','button'); buttonnode3.setAttribute('name','Delete'); buttonnode3.setAttribute("value","Delete('"+ItemName[j]+"');"); buttonnode3.setAttribute("onclick","Delete('"+ItemName[j]+"');"); // for FireFox. This parses through the item name (DelName=item name to delete) buttonnode3.onclick = function() {Delete(ItemName[j]);}; // for Internet Explorer. Again, this parses through DelName tr.appendChild(buttonnode3); (The value name is for testing purposes). As you can see here, it shows fine But when I click delete, I get an 'undefined' error Here is the code for the Delete(); function Code: function Delete(DelName){ // Create function Delete "DelName" parses through item name alert(DelName); // testing for (var ind=0; ind<ItemName.length; ind++) { // Loop through array if(ItemName[ind] == DelName){ // Find item to be deleted ItemName.splice(ind,1); // Delete first record of item name Quantity.splice(ind,1); // Delete first record of its quantity Sum.splice(ind,1); // Delete first record of its sum alert('You have removed ' + DelName); // Alert user document.getElementById("div1").innerHTML=""; // Clear the whole shopping cart document.getElementById("div2").innerHTML=""; document.getElementById("div3").innerHTML=""; ViewShoppingCart(); // Once the cart is cleared, there may still be other items so update it again } } } I've tried doing this var DelName = ItemName[j]; and then change the buttonnode to show DelName and it works however DelName always gets set to the last Item in the array. For example, you delete Dinosaur but it deletes Firemans hat. Can anyone help me out of this hole? I'm sorry if this is in the wrong section... I am not sure how to do it... Here is the coding: Code: function displayTitle(name, x, y){ return name + " <a href='#' onClick='showDirectionsDialog(\""+name+"\", "+x+", "+y+")'><img src='images/direction.png' alt='Get driving directions'/></a>"; } function showDirectionsDialog(name, x, y){ var d=dijit.byId("dialogDirections"); d.set("title", "Get directions to \""+name+"\""); document.getElementById("txtToX").value=x; document.getElementById("txtToY").value=y; d.show(); } function getDirections(){ var frmX=document.getElementById("txtFrmX").value; var frmY=document.getElementById("txtFrmY").value; var toX=document.getElementById("txtToX").value; var toY=document.getElementById("txtToY").value; var routeData = new Route; routeData.routeStops = frmX+","+frmY+";"+toX+","+toY; routeData.routeMode = "DRIVE"; routeData.avoidERP=0; routeData.routeOption = "Shortest"; routeData.GetRoute(showDirections); } function showDirections(routeResults){ if (routeResults.results=="No results"){ alert("No directions found, please try other location."); return; } } Here is the coding I have now: Code: function getDirections() { var routeData = new Route; routeData.routeStops = document.getElementById('txtTheme').value; routeData.routeMode = document.getElementById('txtOtptFlds').value; routeData.avoidERP = document.getElementById('txtExtent').value; routeData.routeOption = "Shortest"; routeData.GetRoute(showRouteData) } function showRouteData(routeResults) { if (routeResults.results=="No results"){ alert("No Route found, please try other location.") return } else if (routeResults.results=="Stops more than nine"){ alert("Number of stops exceed than nine"); return; } directions = routeResults.results.directions[0]; directionFeatures = directions.features; var routeSymbol = new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([0,0,255,0.5])).setWidth(4); var mergedGeometry = new esri.geometry.Polyline() mergedGeometry.addPath(routeResults.results.routes.features[0].geometry.paths[0]) OneMap.map.graphics.clear(); OneMap.map.graphics.add(new esri.Graphic(mergedGeometry, routeSymbol)); //Display the total time and distance of the route document.getElementById("results").innerHTML = "<br /> Total distance: " + directions.summary.totalLength + "<br /> Total time: " + directions.summary.totalTime; //List the directions and create hyperlinks for each route segment for (var i=0;i<directions.features.length;i++) { var feature=directions.features[i] document.getElementById("results").innerHTML= document.getElementById("results").innerHTML + '<br><u>' + parseInt(parseInt(i)+1) + ". " + feature.attributes.text + " (" + feature.attributes.length + ", " + feature.attributes.time + ")</u>" } } I am not sure how to integrate my codings into the other codings. There is a name of the place (lets say London) and a clickable icon by the side. When I click the icon, a dojo toolkit dialog box appear for me to enter my location (the other place, London, will be displayed in the dialog box) Click "Go" to get the directions... I wish to have the directions also placed in a dialog box too... Hi. i,m trying to make a map who show me as position A and a target adress as point B.I have made it so i can choose adress a and adress b from a dropdown but i want to automaticly load my position as possition A then choose position B from a dropdownlist. How can i do this ? Thanks Natrox <!DOCTYPE html> <html> <head> <title>Google Maps JavaScript API v3 Example: Map Geolocation</title> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="UTF-8"> <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" /> <!-- Include the maps javascript with sensor=true because this code is using a sensor (a GPS locator) to determine the user's location. See: http://code.google.com/apis/maps/doc...ecifyingSensor --> <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true&language=nb_NO"></script> <!--<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true&language=nb_NO"> --> <script type="text/javascript"> var map; var directionDisplay; var directionsService; var stepDisplay; var markerArray = []; var initialLocation; //var oslo = new google.maps.LatLng(59.947639, 10.884469); var browserSupportFlag = new Boolean(); function initialize() { directionsService = new google.maps.DirectionsService(); // Create a map and center it on Manhattan. var oslo = new google.maps.LatLng(59.947639, 10.884469); var myOptions = { zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP, center: oslo } map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); // Create a renderer for directions and bind it to the map. var rendererOptions = { map: map } directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions) // Instantiate an info window to hold step text. stepDisplay = new google.maps.InfoWindow(); } function calcRoute() { // First, remove any existing markers from the map. for (i = 0; i < markerArray.length; i++) { markerArray[i].setMap(null); } // Now, clear the array itself. markerArray = []; // Retrieve the start and end locations and create // a DirectionsRequest using DRIVING directions. var start = document.getElementById("sart").value; var end = document.getElementById("end").value; var request = { origin: start, destination: end, travelMode: google.maps.DirectionsTravelMode.DRIVING }; // Route the directions and pass the response to a // function to create markers for each step. directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { var warnings = document.getElementById("warnings_panel"); warnings.innerHTML = "<b>" + response.routes[0].warnings + "</b>"; directionsDisplay.setDirections(response); showSteps(response); } }); } function showSteps(directionResult) { // For each step, place a marker, and add the text to the marker's // info window. Also attach the marker to an array so we // can keep track of it and remove it when calculating new // routes. var myRoute = directionResult.routes[0].legs[0]; for (var i = 0; i < myRoute.steps.length; i++) { var marker = new google.maps.Marker({ position: myRoute.steps[i].start_point, map: map }); attachInstructionText(marker, myRoute.steps[i].instructions); markerArray[i] = marker; } } function attachInstructionText(marker, text) { google.maps.event.addListener(marker, 'click', function() { // Open an info window when the marker is clicked on, // containing the text of the step. stepDisplay.setContent(text); stepDisplay.open(map, marker); }); } // Try HTML5 geolocation if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); var infowindow = new google.maps.InfoWindow({ map: map, position: pos, content: 'Du er her.' }); map.setCenter(pos); }, function() { handleNoGeolocation(true); }); } else { // Browser doesn't support Geolocation handleNoGeolocation(false); } function handleNoGeolocation(errorFlag) { if (errorFlag) { var content = 'Error: The Geolocation service failed.'; } else { var content = 'Error: Your browser doesn\'t support geolocation.'; } var options = { map: map, position: new google.maps.LatLng(60, 105), content: content }; var infowindow = new google.maps.InfoWindow(options); map.setCenter(options.position); } function detectBrowser() { var useragent = navigator.userAgent; var mapdiv = document.getElementById("map_canvas"); if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) { mapdiv.style.width = '100%'; mapdiv.style.height = '100%'; } else { mapdiv.style.width = '600px'; mapdiv.style.height = '800px'; } } google.maps.event.addDomListener(window, 'load', initialize); </script> </head> <body onload="initialize()"> <div style="text-align:center"> <select id="start"> <option value="625 8th Avenue, New York, NY, 10018">Port Authority Bus Terminal</option> <option value="staten island ferry terminal, new york, ny">Staten Island Ferry Terminal</option> <option value="101 E 125th Street, New York, NY">Harlem - 125th St Station</option> </select> <select id="end" onchange="calcRoute();"> <option value="Brubakkveien 14 1083 Oslo">Sigvartsen proffavdeling</option> <option value="Sonja Henies plass 3, 0185 Oslo">Oslo plaza</option> <option value="moma, New York, NY">MOMA</option> <option value="350 5th Ave, New York, NY, 10118">Empire State Building</option> <option value="253 West 125th Street, New York, NY">Apollo Theater</option> <option value="1 Wall St, New York, NY">Wall St</option> </select> </div> <div id="map_canvas"></div> <div id="pos"></div> <div id="warnings_panel"></div> </body> </html> Hi, I am hoping I just need to be pointed in the right direction with this. I have Page1. When Page1 body onloads it uses Ajax to call PartA Within PartA I have a message board so members can write messages which will be sent to my database in PartA[1] and immediately posted for view on to PartA[2]. As I want to have my request to the server updating regularly I want to have PartA[2] on a timed loop to refresh - I do not need the content of PartA[1] to refresh. So the order of events would look like this: Page1 | onload call | v PartA / \ V V PartA[1] PartA[2] (loads once) (constantly refreshes) What I am not sure about is that I have <body> and <head> attributes in Page1 only. I have already used my body onload to call PartA (and can't use it to call PartA[2] before PartA has loaded anyway). I do not want the user to have to click a button or do anything to call up PartA[2]. So my question is how would I get PartA[2] to automatically load within PartA? I hope I have made this clear, but if I haven't let me know and I will try again. Hi, I am a newbie at XML and this issue is proving to be a tough nut to crack for me. My AJAX query returns me an XML response of the following structure for a query on "ind": <countries> <country> <name>India</name> <capital>New Delhi</capital> </country> <country> <name>Indonesia</name> <capital>Jakarta</capital> </country> </countries> How do I transform the XML response into a HTML layout? Particularly, how do I get down to the value at each node?How do I traverse the XML document using JS? Is this (using XML) better than JSON (other than the obvious platform-independence)? Which is better? Thanks! Hi all, I have a string which contains HTML and *possibly* IMG tags. I am trying to extract part of each IMG tag which may be in the string. The string is part of a chat-box message which may or may not contain smilies. Here is a typical line of text, without processing (note I mis-spell the bbcode "quote" so as not to fool this board): Code: [qoute="Krupski"]<img src="./images/smilies/smile.gif" alt=":smile:" title="smile" /> <img src="./images/smilies/thumbsup.gif" alt=":thumbsup:" title="thumbsup" /> <img src="./images/smilies/thumbsdown.gif" alt=":thumbsdown:" title="thumbsdown" />[/qoute] Notice that each image has an "ALT" attribute which contains the smiley code of the smiley image. THAT is what I want to extract. This is the regex I am using to grab each smiley code: Code: txt = txt.replace(/<img(?:.*?):(.*?):(?:.*?)\/>/gi,':$1:'); The weird thing is, the regex grabs the FIRST and LAST of the three, but not the middle one! I'm sure the stupid mistake is sitting right in front of my face, but I'm not seeing it. Any help will be greatly appreciated! Thanks. -- Roger Hi Guys, I am having a small problem in my Javascript when I am using HTTPRequest. I am unable to recieve my Response back from server (Java Servlet) in time. I am using following code; Code: // Following function will simply goes to the Server and check if provided class is present function verifyClass(clsName) { var url = "checkServlet?className=" + clsName; var chkResult = ""; var httpReq = null; // Create an ActiVEX control object according to BRowser we are using httpReq = GetXmlHttpObject(); if (httpReq == null) { alert ("AJAX Request Failed!!! - Your browser does not support AJAX - Skipping CLASS Check."); } else { // First prepare ourself to recieve a response from server // Following code will simply wait untill server finish its response httpReq.onreadystatechange = function(){ if(httpReq.readyState == 4){ chkResult = httpReq.responseText; } } // Setup a request parameters httpReq.open("GET", url, true); // Send the request httpReq.send(null); } // Return the response recieved return chkResult; } I am using FireBug (plugin with my Firefox) to debug the HTML and I can see the response in it but when I am putting 'alert' before return the variable 'chkResult' is empty. Your suggestion will be appreciated; Thanks, -- SJunejo Hello, Im just starting out with java script. I have written the following statement, and for some reason it does not follow up beyond the prompt command. As i type in yes or no - the screen empties. Id be happy if you could tell me where i had gone wrong. My guess its something about the syntax. <!DOCTYPE html> <html> <title>ex</title> <head> <script> var question1 = prompt("do you want to hear a story?"); if (question1 = "yes") {console.log ("once upon a time there was a dragon");} else { console.log ("Maybe listen to a little music?");} </script> </head> <body></body> </html> Hi all, I'm new to php, but managed to get a domail.php working. My form from my html website is sent by the php file to my email address. However, the php echoes a mailresult upon successful sending, but how can I let my website respond to this mailresult?? I'd like to go to a different page, when the mailresult==OK, so something in my html file like if($mailResult==OK){ //go to page saying, your mail has been sent! } OR I could change the "OK" to something more like "Thank you, your mail has been received" in the php file, because this text IS shown in my browser window. Then I would need to know how to make the layout of the window saying this fit my website layout, because now the text is just in a white plain frame.. Hope you guys can help me with either of those two options. Thanks a ton!! Jay Greetings, I have a GMAP2 setup on my website that gives driving directions from Point A to Point B. I want to add functionality that allows a user to alter the directions once the polyline has already been plotted. Working Example: Google Driving Directions My Driving Directions: Green Traffic Driving Directions What javascript do I need to tweak to get the line to be draggable? Thanks in advance for any information and / or assistance. Sincerely, Travis Walters I have the following files in the same directory. I can get index.php displayed but when I enter anything and hit submit I cannot get the or die message to display. I have the files in the c:\xampp\htdocs\ folder and am using http://localhost/index.php from a browser. index.php: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>Username</title> </head> <body> <form action="index.php" method="POST"> Username: <input type="text" name="username"><br> <!--input is text, variable is 'username'--> Password: <input type="password" name="password"> <!--input is password, a type of text, variable is password --> <input type="submit" value="Log in"> <!--input is submit, which is a button, and text on button will read 'Log in'--> </form> </body> </html> login.php: Code: <?php $username = $POST['username']; // setting php var '$username' to equal 'username' from the index.php page (POST method) $password = $POST['password']; if ($username&&$password) //are true { $connect = mysql_connect("localhost", "root", "") //creates connection to database, we're creating a var called or die ("Couldn't connect"); //'$connect' and now we have 3 var's. 'localhost' is the host. 'root' is the //username. mysql_select_db("phplogin") or die("Couldn't find db"); } else die("Please enter a username and a password!"); ?> Hey guys, I am doing a website and the way it is suppose to work is when you click on a link there is a little triangle beside it, so when you click on it the triangle is suppose to face down but more links appear when you click on it. Anyways here is the code if someone could please tell me what im doing wrong? HTML Code: <ul class="menu" id="subnavmenu"> <li><a href="#" onClick="showHide('sublist1');return false;" id="subheading">About Us</a> <ul id="sublist1" style="display:none;"> <li><a href="#">Visit Us</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">Archives Unboxed and Revealed</a></li> </li> </ul> CSS Code: #subnavmenu ul.menu { display: block; overflow:hidden; } JAVASCRIPT Code: function showHide(element_id) { if (document.getElementById && document.getElementById(element_id) && document.getElementById(element_id).style) { var menu = document.getElementById(element_id); var arrow = document.getElementById(element_id + '_arrow'); if (menu.style.display == "block") { menu.style.display = "none"; if (arrow.src) { arrow.src = arrow.src.replace("down","right"); } } else { menu.style.display = "block"; if (arrow.src) { arrow.src = arrow.src.replace("right","down"); } } } } How come when the page below loads, I see the "Ahh!" but not the "HELLO??". The "Ahh!" is generated by the document.write() in JavaScript. Anytime I use it, the other HTML in the page seems to stop loading. Any thoughts? - - - - - - - <html> <head> <title>test</title> </head> <body> <script type="text/javascript"> window.onload = Scream; function Scream() { document.write("Ahh!!"); } </script> <br><br><br><br> HELLO?? </body> </html> i want to update the table -play -win -draw -lost -goals in the following code when i enter the score. (e.g if i select manchester united from drop down1 and chelsea from dropdown 2- i get to update their score. let's say i update their score 1-0. in this case manchester won. i want the record to updated to manchester united as :win 1 - draw 0 - lost 0 goals 1 and chelsea as :win 0 - draw 0 lost 1 goals -1. what shall i do? how do i continue? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" href="../css/foot.css" type="text/css" media="screen"/> </head> <body> <div class="container"> <header> <h1>Online Automated Football League Result</h1> </header> </div> <div class="ball"> <label for="first">Please select the first team:</label> <select id="first"> <option value="team_1">Manchester United</option> <option value="team_2">Liverpool</option> <option value="team_3">Chelsea</option> <option value="team_4">Arsenal</option> <option value="team_5">Manchester City</option> <option value="team_6">Real Madrid</option> <option value="team_7">Bayern Munich</option> <option value="team_8">Barcelona</option> </select> <label for="second">Please select the second team:</label> <select id="second"> <option value="team_1">Manchester United</option> <option value="team_2">Liverpool</option> <option value="team_3">Chelsea</option> <option value="team_4">Arsenal</option> <option value="team_5">Manchester City</option> <option value="team_6">Real Madrid</option> <option value="team_7">Bayern Munich</option> <option value="team_8">Barcelona</option> </select> <label for="username">Enter score for the match (First team and Second team)</label> <input type="text" id="txtbox1" size="2"/> <input type="text" id="txtbox2" size="2"/> <input type="button" value="Update" onclick="updateTable();"/><br/> <div id="err" style="color:Red;"></div> <br/> <table border="1" width="50%" id="score"> <thead> <tr> <th>Team</th> <th>Point</th> <th>Play</th> <th>Win</th> <th>Draw</th> <th>Lost</th> <th>Goal.S</th> <th>Goal.C</th> <th>Goal.D</th> </tr> </thead> <tbody> <tr> <td>Manchester United</td> <td id="team_1">0</td> <td id="team_1">0</td> <td id="team_1">0</td> <td id="team_1">0</td> <td id="team_1">0</td> <td id="team_1">0</td> <td id="team_1">0</td> <td id="team_1">0</td> </tr> <tr> <td>Liverpool</td> <td id="team_2">0</td> <td id="team_2">0</td> <td id="team_2">0</td> <td id="team_2">0</td> <td id="team_2">0</td> <td id="team_2">0</td> <td id="team_2">0</td> <td id="team_2">0</td> </tr> <tr> <td>Chelsea</td> <td id="team_3">0</td> <td id="team_3">0</td> <td id="team_3">0</td> <td id="team_3">0</td> <td id="team_3">0</td> <td id="team_3">0</td> <td id="team_3">0</td> <td id="team_3">0</td> </tr> <tr> <td>Arsenal</td> <td id="team_4">0</td> <td id="team_4">0</td> <td id="team_4">0</td> <td id="team_4">0</td> <td id="team_4">0</td> <td id="team_4">0</td> <td id="team_4">0</td> <td id="team_4">0</td> </tr> <tr> <td>Manchester City</td> <td id="team_5">0</td> <td id="team_5">0</td> <td id="team_5">0</td> <td id="team_5">0</td> <td id="team_5">0</td> <td id="team_5">0</td> <td id="team_5">0</td> <td id="team_5">0</td> </tr> <tr> <td>Real Madrid</td> <td id="team_6">0</td> <td id="team_6">0</td> <td id="team_6">0</td> <td id="team_6">0</td> <td id="team_6">0</td> <td id="team_6">0</td> <td id="team_6">0</td> <td id="team_6">0</td> </tr> <tr> <td>Bayern Munich</td> <td id="team_7">0</td> <td id="team_7">0</td> <td id="team_7">0</td> <td id="team_7">0</td> <td id="team_7">0</td> <td id="team_7">0</td> <td id="team_7">0</td> <td id="team_7">0</td> </tr> <tr> <td>Barcelona</td> <td id="team_8">0</td> <td id="team_8">0</td> <td id="team_8">0</td> <td id="team_8">0</td> <td id="team_8">0</td> <td id="team_8">0</td> <td id="team_8">0</td> <td id="team_8">0</td> </tr> </tbody> </table> </div> <script type="text/javascript"> function updateTable(){ document.getElementById('err').innerHTML = ''; var firstdrop = document.getElementById("first").value; //get team from 1st drop down var seconddrop = document.getElementById("second").value; //get team from 2nd drop down var temp1 = document.getElementById("txtbox1").value; //get score for 1st team var box1 = Number(temp1);//store score of 1st team var temp2 = document.getElementById("txtbox2").value; //get score for 2nd team var box2 = Number(temp2);//store score of 2nd team var tablebox1 = Number(document.getElementById(firstdrop).innerHTML);//store name of 1st team var tablebox2 = Number(document.getElementById(seconddrop).innerHTML);//store name of 2nd team if(temp1 == '' || temp2 == ''){ document.getElementById('err').innerHTML = 'Please enter both scores.'; alert("Please enter both scores."); return; } if(firstdrop != seconddrop){ if(box1 > box2){ document.getElementById(firstdrop).innerHTML = tablebox1 + 3; }else if(box1 < box2){ document.getElementById(seconddrop).innerHTML = tablebox2 + 3; }else{ document.getElementById(firstdrop).innerHTML = tablebox1 + 1; document.getElementById(seconddrop).innerHTML = tablebox2 + 1; } }else{ document.getElementById('err').innerHTML = 'Please select two different teams.'; alert("Please select two different teams."); } } </script> </body> </html> |