1. Technology

JavaScript By Example

DOM Form: 6. Creating Input Fields


Coding our JavaScript would be far simpler if all of the browsers would understand all of our code the same way and allow all of the same things. It is where one or more browsers handle things differently from the others that our JavaScript needs to be more complicated to cater for the difference. The reason for many of these differences is that Internet Explorer actually runs JScript rather than JavaScript and while the two languages are mostly similar with regard to what you can do in JavaScript they are not completely the same (there are of course many additional things you can do with JScript that can't be done with JavaScript at all).

One of the differences between JavaScript and JScript is that JScript (and hence Internet Explorer) does not allow a name attribute to be added or changed on input fields. This means that we can't create an input node and set the name property in order to give an input field a name in JScript the way we do in JavaScript. JScript The only way to create a named input field in JScript is to use a JScript only variant of the createElement method where we define the tag with the name attribute already included. The problem then is that we can't allow that call to be seen when we are running JavaScript as it will cause the script to crash.

Fortunately we can make use of an additional feature of JScript to resolve this problem since JScript also supports conditional comments. By wrapping the JScript only code inside a conditional comment that tests if JScript is running and placing the corresponding JScript code outside the comment but in a way that JScript will treat it as being inside the conditional comment's else block we can deliver the appropriate version of the code to both JScript and JavaScript.

In this example we have a function that creates an input field where we specify both the type of input field to create and the name to use for the field. This function will allow us to forget about this particular difference between JavaScript and JScript as calling the function will create the new input node and add the type and name attributes regardless of which browser you run it in.

var myInput;
createInput = function(typ,nam) {

var newIN;
@if (@_jscript)
newIN = document.createElement("<input name="+nam+"'>");
@else */
newIN = document.createElement("input");
newIN.name = nam;
/* @end
newIN.type = typ;
return newIN;
myInput = createInput('text','email');

Reader Submissions: Help Others By Providing Your Own JavaScript Examples

JavaScript By Example
  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Document Object Model
  7. JavaScript By Example - DOM Form: Creating Input Fields

©2014 About.com. All rights reserved.