View Full Version : Practice Script - Opening a Window

05-02-2012, 10:49 PM
Not sure if I can do this but I'm reading through JavaScript: The Definitive Guide, and I'm going to be posting practice scripts that work. They may not make sense, but they work.

I'd also like responses on how these simple snippets could be used and how they can be made better.

Opening a Window
This is just a simple form with an input box and a "Go" Button. You type in the URL that you want loaded into the new window. Click Go and a new Window Object is created and new window opened. I think.


<form name="frm">
<input name="website" type="text" size="40" maxlength="80" value="type url">

<input name="openpage" type="button" value="Go" onClick="goToPage()">


function goToPage() {
var siteForm = document.getElementsByName("frm")[0];
var webpage = siteForm.website.value;

/* Works! */

05-02-2012, 10:58 PM
The first thing I'd do is to update the HTML from HTML 3.2 to HTML 4 - which means you need to wrap the input fields inside a fieldset or div and not put them directly inside the form tag. Adding a label to the input field so that people know what is expected to be typed ther would also be useful.

Giving the input field an id and getting rid of the unnecessary name references would also alloow the JavaScript to be made more efficient.

Next I'd correct the spelling of onclick - while HTML isn't case sensitive it is better to use the correct capitalisation. It would also be better to make it a submit button rather than just an ordinary button and use onsubmit instead of onclick.

The next step would be to remove the JavaScript from the HTML and attach the event handler from within the script.

After that there are a number of ways to improve it still further but applying the above is probably sufficient for a simple script like this one.

<label for="website">Enter URL:</label><input id="website" type="text" size="40" maxlength="80" value="type url">

<input type="button" value="Go">

function goToPage() {
var siteForm = document.getElementsByid("webpage");
var webpage = siteForm.website.value;

/* Works! */

document.getElementById('webpage').form.onsubmit = function() {goToPage(); return false;};

05-02-2012, 11:07 PM
Yes Yes Yes. I like this place already.
Thank ya buddy.

05-02-2012, 11:12 PM
Giving the input field an id and getting rid of the unnecessary name references […]

I would concretize this a little more and say that the name attribute (on form controls, not the form element itself) is not unnecessary per se since server side scripts make use of them. But in this demonstration that involves just JS and no server side script they can indeed be ommitted. And as said, a name attribute on the form element itself is not valid HTML 4.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum