Quick JavaScript

Simple Scripts that Will Enhance Your Site

There are some things on Web pages that can only be done with JavaScript. Learn how to use JavaScript to do things like:

  • add the date and time to your page
  • make forms easier to fill out

While this is the HTML site, JavaScript is something that people often ask about. Usually without realizing it. "What is the tag to get today's date on the page?" is a common question on the HTML forum and in my email.

There isn't an HTML tag to do this but there is a way to do it with JavaScript.

The Date with JavaScript

It's easy to get the current date (or at least the date on the browser's computer clock, and display it on the screen. It's actually only two lines of JavaScript (and four lines of HTML):

<script language="javascript">
 <!--
 var today = new Date();
 document.write(today);
 //-->
 </script>

See the date script in action

Forms and JavaScript

One way to make forms easier to fill out is to force the cursor to be in the first form field automatically when the page loads. That way, in order to fill out the form, all your reader needs do is start typing. This is just one line of JavaScript in the body tag that interacts with the HTML form:

<body onload="document.test.testing.focus();">
 <form name="test">
 <input type="text" name="testing">
 </form>
 </body>

Note, that the form is named ("test") and the input field is named as well ("testing") and both of those names are used in the JavaScript.

See this form script in action

Another way to save time is to have drop-down menus that take you to the URL without clicking another button. For this script, you are telling the browser that when the select box changes, it should also change the location to the URL in the option value. The select box must be named "URL", otherwise, you need to change the JavaScript:

<form>
 <select name="URL" onchange="window.location.href=this.form.URL.options[this.form.URL.selectedIndex].value">
   <option value="">Choose a site</option>
   <option value="http://webdesign.about.com/">Web Design Front Page</option>
   <option value="http://webdesign.about.com/library/beginning/bl_begin.htm">
   Beginning HTML</option>
   <option value="http://webdesign.about.com/od/javascript/">JavaScript Help</option>
   </select>
 </form>

See the drop-down redirect in action

If you want to add interactivity to your site, JavaScript is a great place to start. And once you learn JavaScript, you'll be that much closer to using Dynamic HTML on your Web sites.