www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 18

Thread: HELP: Simple HTML submit code

  1. #1
    Join Date
    Nov 2010
    Posts
    20

    HELP: Simple HTML submit code

    Hi guys i need some help with my html code. Here's exactly what i want the button to do . I would like visitors to input a valid location and then click the "check locations" button , when that button is clicked , a result would display inside the box below . The problem i am having is that whenever i click the check location button , the result is displayed outside the box . Please i would really appreciate if someone could help me out with this.

    Here is a screen shot explaining how it should work :

    example.jpg


    http://i.imgur.com/2BKgOpP.jpg



    Here is the code below :

    HTML Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Find A Location in Canada</title>
    <meta http-equiv="expires" content="-1" />
    <meta name="resource-type" content="document" />
    <meta name="distribution" content="global" />
    <meta name="robots" content="INDEX, FOLLOW" />
    <meta name="revisit-after" content="1 days" />
    <meta name="rating" content="general" />
    <meta name="author" content="GC Web Studio - www.gcwebstudio.com" />
    <link href="../../style/global.css" rel="stylesheet" type="text/css" />
    <link href="../../style/default/layout.css" rel="stylesheet" type="text/css" />
    <link href="../../style/default/dxmap.css" rel="stylesheet" type="text/css" />
    <script language="javascript" type="text/javascript" src="../../js/jquery.js"></script>
    <script language="javascript" type="text/javascript" src="../../js/gcws.js"></script>
    <script src="some_script_name.js"></script>
    
    </head>
    
    
    <body onLoad="load()" onUnload="GUnload()">
    <div id="enclosure">
            <div id="header">
        	
            <div class="navs">
            	<div class="nav-top">
                	<dl>
                    	<dd class="nav-top-op nav-top-op-location"><Find a Location</dd>
                    	<dd class="nav-top-op">English</dd>
                        <dd class="nav-top-op">Franšais</dd>
                        <dd class="nav-top-op nav-top-op-last">Site Map</dd>
                    </dl>
                </div>
                <div class="clear"></div>
                <div class="nav-main">
                            	<dl>
                    	<dd class="nav-main-op">HOME</dd>
                        <dd class="nav-main-op">SERVICES</dd>
                        <dd class="nav-main-op">TECHNOLOGY</dd>
                        <dd class="nav-main-op">ABOUT US</dd>
                        <dd class="nav-main-op nav-main-op-last">CONTACT US</dd>
                    </dl>
                            </div>
                <div class="clear"></div>
            </div>
            <div class="clear"></div>
        </div>    <div id="wrapper">
        	
        	<div id="main">
            	<div id="left">
                                                    
                    <div class="left-menu">
                    	<h4>Contact Us</h4>
                    	<div class="left-menu-holder">
                        	<ul>
                            		
                            		<li class="left-menu-top-op">
                                    <span>Contact Information</span>
                                    </li>
    						
                            		
                            		<li class="left-menu-top-op">
                                    <span>Find a Location</span>
                                    </li>
    						
                                                    		<li>
                                        <ul>
                                                    
                                                <li class="left-menu-top-sub left-menu-op-active">
                                                Canada
                                                </li>
                                                
                                                                        
                                                <li class="left-menu-top-sub">
                                                United States
                                                </li>
                                                
                                                                                    </ul>
                                    </li>
                                                    </ul>
                        </div>
                    </div>            </div>
            	<div id="content">
                			        
            <div class="breadcrumb">Home&raquo; </div>                <div class="content-inner">
                    	<h1>Find Location</h1>
                        
                                            <script type="text/javascript"> 
    							<!--//--><![CDATA[//><!--
    								var imagePath = "../../images/dx_map/index.html";
    								var searchPath = "ajax18a5.html?action=dx_map";
    								var baseURL = "../../index.html";
    								var centerpoint = 60;
    							//--><!]]>
    							</script>                    <div>
                            City, Province -or- Postal Code:  <input id="cityName" type="text" /> <input type="button" value="Check Locations" onclick="_CheckLocation()" />
    <div id="cityInformation"></div>
                         
                                <input type="hidden" name="country" value="canada" id="country" />
                            <!--<input type="button" onclick="searchLocations()" value="Search Locations"/>-->
                            &nbsp;&nbsp;<br />
                          <br />
                          
                        </div>
                        
                        <div id="search-locator">
    
                            <table cellpadding="0" cellspacing="0">                     
                              <tbody>                     
                                <tr>                   
                                  <td width="200" valign="top" bgcolor="white">                     
                                    <div id="sidebar"></div>                    
                                  </td>                    
                                </tr>                     
                              </tbody>                    
                            </table>
                        
                          </div>    
                     				 <script type="text/javascript">
    				 	$j(document).ready(function() {
    						load();
    					});
    				 </script>
                        
                    </div>
            	</div>
               
                <div class="clear"></div>
    		</div>
                </div>
            <div id="footer">
        	<div class="footer-cities">
            	
            <div class="footer-holder">
                
                <div class="footer-links-copyright">
                    <div class="footer-links">
                        <dl>
                            <dd class="footer-link-op">Home</dd>
                            <dd class="footer-link-op">Contact Us</dd>
                            <dd class="footer-link-op">Career Opportunities</dd>
                            <dd class="footer-link-op">Resources</dd>
                            <dd class="footer-link-op footer-link-op-last">Privacy Policy</dd>
                        </dl>
                        <div class="clear"></div>
                    </div>
                   <a href="https://plus.google.com/114299192543146794735" rel="publisher"><img src="../../images/GooglePlusIcon.png" style="width: 20px; height: 20px; float: left; margin-top: 10px;"/></a>
                    <div class="footer-copyright">
                    	<div style="float:right">&copy; 2014 Demo Inc. All Rights Reserved.</div>                                                           
                    </div>
                    <div class="clear"></div> 
                </div>           
                <div class="clear"></div>                                 
            </div>
            
            <div class="transforce" style="display:none"><a href="http://www.transforce.ca/" target="_blank"><img src="../../images/transforce_logo.jpg" border="0" alt="TransForce" /></a></div>
        </div></div>
    
    </body>
    
    
    </html>

    SOME_SCRIPT_NAME.JS

    var $locations = {
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345",
    "city_name": "123 Address St<br>Some City, ST 12345"
    };
    function _CitySearch($a, $b) {
    for(var $c in $b) {
    if($a.toLowerCase() == $c.toLowerCase()) return $b[$c];
    }
    return "The city you entered was not valid!";
    }

    function _CheckLocation() {
    var $cityName = document.getElementById('cityName').value;
    document.getElementById('cityInformation').innerHTML = _CitySearch($cityName, $locations);
    }
    Attached Images Attached Images

  2. #2
    Join Date
    Nov 2010
    Posts
    20
    Would really appreciate if someone could help. Thanks

  3. #3
    Join Date
    Jun 2014
    Location
    Cairns - Australia
    Posts
    78
    Dude are you taken the piss?... would kind of help if the output js was in the table and not after it?????

    Code:
    <table cellpadding="0" cellspacing="0">                     
                              <tbody>                     
                                <tr>                   
                                  <td width="200" valign="top" bgcolor="white">  
    
    
                                       ??????????
    
                       
                                    <div id="sidebar"></div>                    
                                  </td>                    
                                </tr>                     
                              </tbody>                    
                            </table>
                        
                          </div>    
    
    
                     				 <script type="text/javascript">
    				 	$j(document).ready(function() {                  ????
    						load();
    					});
    				 </script>
    
    
                        
                    </div>
            	</div>

  4. #4
    Join Date
    Nov 2010
    Posts
    20
    Hi Code-tard , Thanks for replying unfortunately I don't really understand what you mean . Please I would appreciate if you could explain a little better. Thanks

  5. #5
    Join Date
    Jun 2014
    Location
    Cairns - Australia
    Posts
    78
    Your output script is homeless?


    This bit of code:

    <script type="text/javascript">
    $j(document).ready(function() {
    load();
    });
    </script>

    Its not assigned to any location on the page?.. so its just showing up first available spot...
    Put in the table or Div tags

    Try where I put the long line of question marks.. in the table not under it!

  6. #6
    Join Date
    Nov 2010
    Posts
    20
    I did what you suggested

    <table cellpadding="0" cellspacing="0">
    <tbody>
    <tr>
    <td width="200" valign="top" bgcolor="white">

    <script type="text/javascript">
    $j(document).ready(function() {
    load();
    });
    </script>
    <div id="sidebar"></div>
    </td>
    </tr>
    </tbody>
    </table>

    </div>


    </div>
    </div>
    The result still displays outside the box

  7. #7
    Join Date
    Jun 2014
    Location
    Cairns - Australia
    Posts
    78
    Hey Mucho.. sorry mate, truth is Im just a long time newbie myself.. so its a case of the blind leading the blind here.. and I try to help with the little things where I can in hopes to give the big fish more time to help with the big problems....

    This script placement error was an easy spot.. but to help more would really need to see the css files.. are you able to link the page?... To be honest dude.. something about the whole page design feels wrong.. have you mixed and matched parts of scripts?.. You've got 3 js noLoad commands, 2 in body tag 1 in page.. something about that is not right?...

  8. #8
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,346
    This isn't JavaScript either, its a framework like JQuery.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  9. #9
    Join Date
    Nov 2010
    Posts
    20
    Quote Originally Posted by \\.\ View Post
    This isn't JavaScript either, its a framework like JQuery.
    So what do you suggest i do ?

    @code-tard i tried to paste the css here but i got an error message saying the characters are too long. So i have zipped the css files and i have uploaded the zip file here. Please @code-tard and \\.\;1347095 , i would really appreciate some assistance with this . Thanks a lot
    Attached Files Attached Files

  10. #10
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,346
    You are using a mix of JQuery and JavaScript, JQuery is written in JavaScript, which has its advantages, I am not a fan of it and haven't bothered learning about it because IMHO you are better off learning JavaScript.

    If this was my project, it would be mostly server-side and not client-side coding, that way your address matching could be put in to a database.

    Does your server support PHP and MySQL?

    If it does then you will be better off creating a database and using PHP to query the database for the address information.

    I am not going to confuse you with code but it would serve you to find out what server-side support you have and then take thing from that point forward.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  11. #11
    Join Date
    Oct 2013
    Posts
    484
    Quote Originally Posted by \\.\ View Post
    This isn't JavaScript either, its a framework like JQuery.
    Actually more like a really bad implementation of a mapping API that uses JQuery. It has the smell of copy/pasting bits and pieces from the code/source of someone else's page and trying to make it work.

    Be that as it may...

    Validate your code first and foremost. There's issues with a lot of things. One major one is that, since you are using an XHTML1.0 TRANSITIONAL DOCTYPE, onload="" and onunload="" are not valid attributes for <body>. In fact onunload is a HTML5-only attribute according to my resource. Consider changing to that DOCTYPE.

    Second, you are using onload="load()" and later down the page using:
    Code:
    $j(document).ready(function() {
    	load();
    });
    I know almost nothing about JQuery other than to (sometimes badly) copy/paste code. However it seems that both onload="" and $j(document).ready(function() are trying to do the exact same thing -- execute the load() function on pageload. There may be conflicts there.

    Any browser's "console" can help you to sort out problems such as resources not found, JS coding errors, CSS issues, etc. Learn to use it. F12 brings it up in Chrome, FF, and IE.

    But until you post a link there's not much anyone can help you with. Kudos to Code-tard for being brave and game enough to take stabs at it.

  12. #12
    Join Date
    May 2014
    Posts
    900
    So far folks have pointed out a lot of problems, but there's even more in there that's just some serious "what the?!?!?"

    I may touch upon some things already mentioned, and not all of this is related to your immediate issue -- but going down the list from the top:

    1) Mulitple load methods as Kevin2 mentioned -- really you shouldn't even have the onload attribute anymore.

    2) 4 Tranny was meant for updating old HTML 3.2 sites with modern tags, NOT for writing new ones.

    3) NEVER set expires to never...

    4) two thirds your METADATA absolutely NOTHING cares about, that's just code bloat.

    5) There is no such thing as INDEX and FOLLOW on a robots meta -- you want it indexed and followed, DON'T include the META!

    6) No media targets on your style LINK.

    7) Scripts load faster if put in BODY as they will start downloading sooner. Since the scripting you have seems to be all hooks, put it right before the </body> tag instead of inside HEAD... and that should be ALL your scripting going together AFTER your semantic markup.

    8) There's no such thing as onunload by the HTML specifications, that's a JS thing -- even if FF, IE and Safari support it, Chrome and Opera do not as again, BODY does not have a ONUNLOAD attribute. Again though like onload you should be hooking it from the script not having the markup hook the scripting with attributes. I really think they need to strike the various onevent attributes from HTML entirely.

    9) Ease up on the DIV -- given your appearance in the screenshots about two thirds of them belong in the trash can.

    10) what on earth makes a menu a definition list -- you don't even have TERMS you are defining?!? If you don't have DT, you have no business using DL or DD, that's UL and LI's job!

    11) Too many classes - if every single element inside a parent (like a DL or DIV with an ID on it) is getting the same class, NONE of them need classes. Use child selectors to target off the parent!

    12) Bizzare heading orders. How can you start a level 4 depth subsection without a H1, H2, or H3 preceeding it? Why do you have a H1 AFTER the H4? You want content-first, build content-first.

    13) Table for... uhm... yeah, what exactly?!?

    14) Clearing DIV -- this is 2014, not 2001. There is NO reason to use those in modern HTML or CSS as there are more than enough ways to trip float wrapping behavior if needed without adding pointless bloat to the markup. ...and no, I don't mean "clearfix"!

    15) don't wait for onload if all you're doing is DOM manipulation. Just run it right before </body> as the DOM will already be built by then!

    16) If you are declaring multiple variables in a row, you only need to say VAR once, you can then comma delimit them.

    17) if you made this a proper form, you could trap onsubmit to run your scripting AND have the possibility of a scripting off fallback that performs the same actions but with a page-load. As the unwritten rule of JS goes, "If you can't make a page that works without JavaScript first, you likely have no business adding scripting to it!"

    So the markup should probably go something like this:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html
    	xmlns="http://www.w3.org/1999/xhtml"
    	lang="en"
    	xml:lang="en"
    ><head>
    
    <meta
    	http-equiv="Content-Type"
    	content="text/html; charset=utf-8"
    />
    
    <meta
    	http-equiv="Content-Language"
    	content="en"
    />
    
    <meta
    	name="viewport"
    	content="width=device-width; height=device-height; initial-scale=1.0"
    />
    
    <link
    	type="text/css"
    	rel="stylesheet"
    	href="screen.css"
    	media="screen,projection,tv"
    />
    
    <title>
    	Find A Location in Canada
    </title>
    
    </head><body>
    
    <div id="top" class="widthWrapper">
    	
    	<h1>
    		Site Title
    		<!-- everything on the page should be a subsection of the H1 -->
    	</h1>
    	
    	<!-- you had some weird DL here for Christmas only knows what -->
    	
    	<ul id="mainMenu">
    		<!--
    			if you're going to make a menu, mark it up properly with anchors BEFORE
    			you start throwing style at it!
    		-->
    		<li><a href="#">HOME</li>
    		<li><a href="#">SERVICES</li>
    		<li><a href="#">TECHNOLOGY</li>
    		<li><a href="#">ABOUT US</li>
    		<li><a href="#">CONTACT US</li>
    	</ul>
    	
    	<div class="contentWrapper"><div id="content">
    	
    		<ul class="breadcrumbs">
    			<li>Home</li>
    		</ul>
    		
    		<form action="#" method="get" id="findLocation">
    			<h2>Find Location</h2>
    			<fieldset>
    				<label for="findCityName">City, Province -or- Postal Code:</label>
    				<input type="text" id="findCityName" name="cityName" type="text" />
    				<select id="findCountry" name="country">
    					<option selected="selected">Canada</option>
    					<option>United States</option>
    				</select>
    			</fieldset>
    			<div class="submitsAndHiddens">
    				<input type="submit" class="submit" value="Check Locations" />
    				<input type="hidden" name="country" value="canada" id="country" />
    			<!-- .submitsAndHiddens --></div>
    		</form>
    		
    		<div id="cityInformation"></div>
    		
    	<!-- #content, .contentWrapper --></div></div>
    		
    	<div id="extras">
    		<h2>Contact Us</h2>
    		<ul class="menu">
    			<li class="major"><a href="#">Contact Information</a></li>
    			<li class="major"><a href="#">Find a Location</a></li>
    			<li><a href="#">Canada</a></li>
    			<li><a href="#">United States</li>
    		</ul>
    	<!-- #extras --></div>
    	
    	<div id="footer">
    		<ul>
    			<li><a href="#">Home</a></li>
    			<li><a href="#">Resources</a></li>
    		</ul><ul>
    			<li><a href="#">Contact Us</a></li>
    			<li><a href="#">Resources</a></li>
    		</ul><ul>
    			<li><a href="#">Career Opportunities</a></li>
    		</ul>
    		<a href="https://plus.google.com/114299192543146794735" rel="publisher">
    			<img
    				src="../../images/GooglePlusIcon.png"
    				width="20" height="20"
    				alt="Google+"
    				class="socialIcon"
    			/>
    		</a>
    		&copy; 2014 Demo Inc. All Rights Reserved.
    		
    	<!-- #footer --></div>
    	
    <!-- #top.widthWrapper --></div>
    									
    <script type="text/javascript"><!--
    	var
    		imagePath = '/images/dx_map/index.html',
    		searchPath = 'ajax18a5.html?action=dx_map',
    		baseURL = '/index.html',
    		centerpoint = 60;
    --></script>
    <script type="text/javascript" src="getLocations.js"></script>
    	
    </body></html>
    Though there's a bigger problem. Your sample script:

    Code:
    var $locations = {
     "city_name": "123 Address St<br>Some City, ST 12345",
     "city_name": "123 Address St<br>Some City, ST 12345",
     "city_name": "123 Address St<br>Some City, ST 12345",
     "city_name": "123 Address St<br>Some City, ST 12345",
     "city_name": "123 Address St<br>Some City, ST 12345",
    Do we see a problem here? You can't have the same object property more than once, that script will crash and prevent ANY of your scripting from running.

    Gimme a few minutes and I'll see if I can toss together a working demo of what I think you are trying to do here.

    ... and I don't know why you guys are talking about jQ since the offending code doesn't use it. He just seems to be slapping dollar signs on variables for Christmas knows what reason.
    Java is to JavaScript as Ham is to Hamburger.

  13. #13
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,346
    The basics are to establish what the OP needs, is this a community based project or is it part of a course at college or school.

    It is also important to establish what the OP has access to on the web host, PHP / MySQL would be helpful as it makes the project easily scalable.

    My personal thoughts are that JQuery et al can be left out of the picture and the OP can learn JS from the ground up.

    To start with, the objective... Is this going to be some sort of directory?
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  14. #14
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,346
    IMHO the simplest of all these tasks can be performed by way of a few simple options, I propose an Array of Objects that can be searched with a search term that will look at all the parts of the address so that a street name may pull more than one city address or more than one address in the city may be listed or a part postcode could return an address.

    I still think that this can be achieve better results with server side data and scripting which the form then polls either as an AJAX call or as a form submission.

    HTML Code:
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Untitled Document</title>
    <script>
    function find_address(searchTerm){
    	for(f=0,result=[]; f<locations.length; f++){
    		for( l in locations[f] ){
    			var tmp = locations[f][l].toLowerCase();
    			if( tmp == searchTerm.toLowerCase() || tmp.match( RegExp( searchTerm , "i" ) ) )
    				result.push(locations[f]);
    		}
    	}
    return result;
    }
    
    function add_address(address,city,postcode){
    	// push an object in to the array
    	locations.push({"address":address,"city":city,"postcode":postcode});
    }
    
    var locations = [];
    add_address("123 Wiggins St","Somecity1","ST 12345");
    add_address("1 Address St","London","LL1 1LL");
    add_address("123 Address St","London","ST 12345");
    add_address("123 Address St","Somecity4","ST 12345");
    add_address("123 Wiggings Street","Manchester","M4 4AB");
    add_address("123 Address St","Somecity6","ST 12345");
    add_address("123 Address St","Somecity7","ST 12345");
    
    
    function checkThis(o){
    	x = find_address( o.cityselection.value );
    	for(y=0,str=""; y<x.length; y++){
    		str += "<br>" + x[y].address + "<br>" + x[y].city + "<br>" + x[y].postcode + "<br><hr>"; 
    	}
    	
    	document.getElementById("output").innerHTML = (x.length) ? str : "Nothing Found";
    }
    
    </script>
    </head>
    
    <body>
    <form name="city" action="javascript:;" onsubmit="return checkThis(this);">
    	<input name="cityselection" value="" type="text" />
    	<input type="submit" value="Submit" name="submit" /> 
    </form>
    <div id="output"></div>
    </body>
    </html>
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  15. #15
    Join Date
    May 2014
    Posts
    900
    @ \\.\ see, you're putting SCRIPT in head -- WHY?

    In any case, here's what I came up with: (fixing some typo's in the markup I made above)
    http://www.cutcodedown.com/for_other.../template.html

    I added a select for country and made the 'location' variables data structure reflect that. The script like a good little doobie attaches itself to the markup instead of those outdated garbage 'onevent' attributes in the markup...

    To break down the script:
    http://www.cutcodedown.com/for_other...etLocations.js

    First I put everything into a anonymous function to isolate the routine's scope so other scripts don't interfere with it. The end of the anonymous function passes document as d, to save some typing, and strangely enough, speed up execution a hair. Cute trick Google uses in some of their scripts, I like it.

    Next is the locations variable for the quick demo of how to plug in content. I may try later tonight or tomorrow tossing together an actual demo of how I'd handle that as AJAX.

    I like to grab all the elements I'm going to manipulate up-front ahead of time. getElementById is slow, so if we can do it once at the start (while things like CSS are being loaded in the background) it will make when they type in a value run faster.

    Next up are dumbed down versions of some handy functions akin to those in my elementals.js library. For a simple standalone I don't really use 'libraries' or 'frameworks'.

    The first lib function 'flush' just deletes all child nodes from element 'e' -- this is akin to doing e.innerHTML = ''; except that it runs faster and doesn't force a re-parse of the entire page's markup. (the whole reason we're SUPPOSED to stop using innerHTML)

    Next is my 'make' function which I use to generate tags as DOM nodes. tagName is pretty obvious, the content variable can be either text or an another object node, attribs is an object of attributes (if desired) -- both 'content' and 'attribs' can be passed false if you don't want to assign values. Finally the 'parent' variable indicates what element you want to attach this new DOM node to, if any.

    I tossed in a simple cross-browser eventAdd function to handle adding our event listeners -- again, good scripts should hook the markup, not the other way around.

    'eventPrevent' stops an event from bubbling, propagating, defaulting or whatever the devil else each browser maker of the past two decades has felt like calling it. This way when we trap the form's submit, we can make it not submit as our scripting is handling it.

    ... coming out of the little lib functions, we add our submit event to the form. We make sure we have the actual event handler so we can cancel it (or pull info from it if need be), then flush out the contents of 'infoBox'. Pulling the city and country name I change them to lower case for the array lookups, then test if they exist. We have to test for [country] and [country][city] separately as if 'country' doesn't exist, locations[country][city] will crash the system. In a production version of this you'd run your AJAX here.

    If you get valid values, I add a H3 saying that matches were found as a heading to the UL that follows. I put everything into an unordered list since this is a list of results, though depending on the complexity of the results you may want to change that. I save the new UL to a variable so we can plug values into it, while appending it to infoBox.

    You really shouldn't do "for (var i in locations)" or so forth on arrays -- it's a object construct, keep it on objects. We loop through the resulting array, and make a bunch of LI plugging the plaintext into them as their content, appending them to the UL.

    If we don't find a match, make a p.errorBox saying so instead.

    Finally, we prevent this event from propagating/continuing.

    ... and that's how it's done.
    Last edited by deathshadow; 07-19-2014 at 10:43 PM.
    Java is to JavaScript as Ham is to Hamburger.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles