Hi Friends,

In this blog we will discuss how to set your field values you just need to required basic knowledge of HTML 5 & JavaScript.

The user has entered her ZIP code in a form field. You want to save her the trouble of
entering the city and state. So when she clicks out of the field, you fill in the city field for her.

This is the code.

<!DOCTYPE html>  
 <html>  
 <head>  
   <meta charset="utf-8" />  
   <meta http-equiv="X-UA-Compatible" content="IE=edge">  
   <title>Zip Code</title>  
   <meta name="viewport" content="width=device-width, initial-scale=1">  
   <link rel="stylesheet" type="text/css" media="screen" href="main.css" />  
 </head>  
 <body>  
       <form>  
         Enter Your City Zip Code:<br><br>  
         <input type="text" id="zip" size="50" onBlur="fillCity();"> <br>  
         <br>City Name:<br><br>  
         <input type="text" id="city" size="50">  
       </form>  
 </body>  
   

   function fillCity() {  
     var cityName;  
     var zipEnterd = document.getElementById('zip').value;  
     switch (zipEnterd) {  
       case "10001" :  
       cityName = "New York";  
       break;  
       case "02116" :  
       cityName = "Boston";  
       break;  
       case "20036" :  
       cityName = "Washington DC";  
       break;  
       case "19147" :  
       cityName = "Philadelphia";  
       break;  
       case "30303" :  
       cityName = "Atlanta";  
       break;  
       case "33122" :  
       cityName = "Miami";  
       break  
       default:  
       cityName = "City Not Found";  
       break;  
     }  
     document.getElementById("city").value = cityName;  
   }  
   
 </html>  

 

In this case, the function assigns the value found in the ZIP field to a variable. Then, using a switch statement, it matches the ZIP to a city name and assigns that name to second variable. Then, using the variable, it places the city name in the city field.

This is result screen shots.

zip1

When the user  enters his zip code and clicks out of the ZIP field, the onBlur event triggers the fillCity function and city name has been showed .

zip2

ThankQ for watching and reading my post.

Happy Coding!