Categories
JavaScript Tutorials

Detecting Arrays

Ever since ECMAScript 3 was defined, one of the classic problems has been truly determining whether a given object is an array. When dealing with a single web page, and therefore a single global scope, the instanceof operator works well:

if (value instanceof Array){
  //do something on the array
}

The one problem with instanceof is that it assumes a single global execution context. If you are dealing with multiple frames in a web page, you’re really dealing with two distinct global execution contexts and therefore two versions of the Array constructor. If you were to pass an array from one frame into a second frame, that array has a different constructor function than an array created natively in the second frame. To work around this problem, ECMAScript 5 introduced the Array.isArray() method. The purpose of this method is to definitively determine if a given value is an array regardless of the global execution context in which it was created. Example usage:

if (Array.isArray(value)){
  //do something on the array
}
Categories
JavaScript Tutorials

The length property

Array properties and methods

  • The length property
  • Detecting Arrays
  • Conversion Methods
  • Reduction Methods

Advanced Built-in Objects

  • The Date Object
  • The RegExp Object

Advanced expressions

  • Object and Array initializers
  • Function Definition Expressions
  • Invocation Expressions

Advanced Functions

  • Self-invoking Functions
  • Inner (Private) Functions
  • Functions that return Functions

Function scope and closure

  • Scope in JavaScript
  • Lexical Scope
  • Closure
  • Closures in a Loop

Advanced Objects

  • Constructor Functions
  • Passing Objects
  • Comparing Objects

Advanced topics

  • Compiled vs Scripting languages
  • Hoisting
  • The this keyword

A unique characteristic of length is that it’s not read-only. By setting the length property, you can easily remove items from or add items to the end of the array. Consider this example:

var colors = ['red', 'blue', 'green']; //creates an array with three strings
colors.length = 2;
alert(colors[2]); //undefined

Here, the array colors start out with three values. Setting the length to 2 removes the last item (in position 2), making it no longer accessible using colors[2]. If the length were set to a number greater than the number of items in the array, the new items would each get filled with the value of undefined, such as in this example:

var colors = ['red', 'blue', 'green']; //creates an array with three strings
colors.length = 4;
alert(colors[3]); //undefined

This code sets the length of the colors array to 4 even though it contains only three items. Position 3 does not exist in the array, so trying to access its value results in the special value undefined being returned. The length property can also be helpful in adding items to the end of an array, as in this example:

var colors = ['red', 'blue', 'green']; //creates an array with three strings
colors[colors.length] = 'black'; //add a color (position 3)
colors[colors.length] = 'brown'; //add another color (position 4)

The last item in an array is always at position length – 1, so the next available open slot is at position length. Each time an item is added after the last one in the array, the length property is automatically updated to reflect the change. That means colors[colors.length] assigns a value to position 3 in the second line of this example and to position 4 in the last line. The new length is automatically calculated when an item is placed into a position that’s outside of the current array size, which is done by adding 1 to the position, as in this example:

var colors = ['red', 'blue', 'green']; //creates an array with three strings
colors[99] = 'black'; //add a color (position 3)
alert(colors.length); //100

In this code, the colors array has a value inserted into position 99, resulting in a new length of 100 (99 + 1). Each of the other items, positions 3 through 98, doesn’t actually exist and so returns undefined when accessed.

Categories
JavaScript Tutorials

Advanced JavaScript

Array properties and methods

Advanced Built-in Objects

Advanced expressions

Advanced Functions

Function scope and closure

  • Scope in JavaScript
  • Lexical Scope
  • Closure
  • Closures in a Loop

Advanced Objects

  • Constructor Functions
  • Passing Objects
  • Comparing Objects

Advanced topics

  • Compiled vs Scripting languages
  • Hoisting
  • The this keyword

A unique characteristic of length is that it’s not read-only. By setting the length property, you can easily remove items from or add items to the end of the array. Consider this example:

var colors = ['red', 'blue', 'green']; //creates an array with three strings
colors.length = 2;
alert(colors[2]); //undefined

Here, the array colors start out with three values. Setting the length to 2 removes the last item (in position 2), making it no longer accessible using colors[2]. If the length were set to a number greater than the number of items in the array, the new items would each get filled with the value of undefined, such as in this example:

var colors = ['red', 'blue', 'green']; //creates an array with three strings
colors.length = 4;
alert(colors[3]); //undefined

This code sets the length of the colors array to 4 even though it contains only three items. Position 3 does not exist in the array, so trying to access its value results in the special value undefined being returned. The length property can also be helpful in adding items to the end of an array, as in this example:

var colors = ['red', 'blue', 'green']; //creates an array with three strings
colors[colors.length] = 'black'; //add a color (position 3)
colors[colors.length] = 'brown'; //add another color (position 4)

The last item in an array is always at position length – 1, so the next available open slot is at position length. Each time an item is added after the last one in the array, the length property is automatically updated to reflect the change. That means colors[colors.length] assigns a value to position 3 in the second line of this example and to position 4 in the last line. The new length is automatically calculated when an item is placed into a position that’s outside of the current array size, which is done by adding 1 to the position, as in this example:

var colors = ['red', 'blue', 'green']; //creates an array with three strings
colors[99] = 'black'; //add a color (position 3)
alert(colors.length); //100

In this code, the colors array has a value inserted into position 99, resulting in a new length of 100 (99 + 1). Each of the other items, positions 3 through 98, doesn’t actually exist and so returns undefined when accessed.

Categories
JavaScript Tutorials

Putting Objects in Motion with JSON

The main reason JSON is so easy to use is because it’s already in a format that JavaScript can work with, so no conversion is necessary. For example, Listing 16-4 shows a JSON file containing information about this book.

Listing 16-4: JSON Data Describing Coding with JavaScript For Dummies

<html>
  <head>
    <title>Displaying JSON Data</title>
    <script>
      window.addEventListener('load', init, false);
      function init(e) {
        document
          .getElementById('myButton')
          .addEventListener('click', documentLoader, false);
      }
      function reqListener() {
        // convert the string from the file to an object with JSON.parse
        var obj = JSON.parse(this.responseText);
        // display the object's data like any object
        document.getElementById('book_title').innerHTML = obj.book_title;
        document.getElementById('book_author').innerHTML = obj.book_author;
        document.getElementById('summary').innerHTML = obj.summary;
      }
      function documentLoader() {
        var oReq = new XMLHttpRequest();
        oReq.onload = reqListener;
        oReq.open('get', 'listing16-4.json', true);
        oReq.send();
      }
    </script>
  </head>
  <body>
    <form id="myForm">
      <button id="myButton" type="button">Click to Load</button>
    </form>
    <h1>Book Title</h1>
    <div id="book_title"></div>
    <h2>Authors</h2>
    <div id="book_author"></div>
    <h2>Summary</h2>
    <div id="summary"></div>
  </body>
</html>

The key to displaying any JSON data that’s brought into a JavaScript Document from an external source is to convert it from a string to an object using the JSON.parse method. After you do that, you can access the values within the JSON file using dot notation or bracket notation as you would access the properties of any JavaScript object. Figure 16-10 shows the results of running Listing 16-5 in a web browser and pressing the button to load the JSON data.

Categories
JavaScript Tutorials

Using the XMLHttpRequest object

The XMLHttpRequest object provides a way for web browsers to request data from a URL without having to refresh the page.

The XMLHttpRequest object was created and implemented first by Microsoft in its Internet Explorer browser and has since become a web standard that has been adopted by every modern web browser. You can use the methods and properties of the XMLHttpRequest object to retrieve data from a remote server or your local server. Despite its name, the XMLHttpRequest object can get other types of data besides XML, and it can even use different protocols to get the data besides HTTP. Listing 16-1 shows how you can use XMLHttpRequest to load all the countries data from a url into the current HTML document.

Listing 16-1: Using XMLHttpRequest to Load External Data

<html>
  <head>
    <title>Loading External Data</title>
    <script>
      window.addEventListener('load',init);
      function init(e){
        document.getElementById('myButton').addEventListener('click',urlLoader);
      }
      function reqListener () {
        document.getElementById('content').innerHTML = this.responseText;
      }
      function urlLoader(){
        var oReq = new XMLHttpRequest();
        oReq.onload = reqListener;
        oReq.open("get", "https://restcountries.com/v2/all", true);
        oReq.send();
      }
    </script>
  </head>
  <body>
    <form id="myForm">
      <button id="myButton" type="button">Click to Load</button>
    </form>
    <div id="content"></div>
  </body>
</html>

The first line of code inside the function creates the new XMLHttpRequest object and gives it the name of oReq:

var oReq = new XMLHttpRequest();

The methods and properties of the XMLHttpRequest object are accessible through the oReq object.

This second line assigns a function, reqListener, to the onload event of the oReq object. The purpose of this is to cause the reqListener function to be called when oReq loads a document:

oReq.onload = reqListener;

The third line uses the open method to create a request:

oReq.open("get", "https://restcountries.com/v2/all", true);

In this case, the function uses the HTTP GET method to load the data from the url. The third parameter is the async argument. It specifies whether the request should be asynchronous. If it’s set to false, the send method won’t return until the request is complete. If it’s set to true, notifications about the completion of the request will be provided through event listeners. Because the event listener is set to listen for the load event, an asynchronous request is what’s desired. It’s unlikely that you’ll run into a situation where you’ll want to set the async argument to false. In fact, some browsers have begun to just ignore this argument if it’s set to false and to treat it as if it’s true either way because of the bad effect on the user experience that synchronous requests have. The last line in the urlLoader function actually sends the requests that you created with the open method:

oReq.send(); 

The open method will get the latest version of the requested url. So-called live-data applications often use loops to repeatedly request updated data from a server using AJAX.

Categories
JavaScript Tutorials

Viewing AJAX in action

In Figure 16-3, shown in the preceding section, the Chrome Developer Tools window is open to the Network tab. The Network tab shows all network activity involving the current web page. When a page is loading, this includes the requests and downloads of the page’s HTML, CSS, JavaScript, and images. After the page is loaded, the Network tab also displays the asynchronous HTTP requests and responses that make AJAX possible. Follow these steps to view AJAX requests and responses in Chrome:

1. Open your Chrome web browser and navigate to http://www.wunderground.com/wundermap.

2. Open your Chrome Developer Tools by using the Chrome menu or by pressing Command+Option+I (on Mac) or Control+Shift+I (on Windows).

3. Open the Network tab.

Your Developer Tools window should now resemble Figure 16-4. You may want to drag the top border of the Developer Tools to make it larger at this point. Don’t worry if this makes the content area of the browser too small to use. What’s going on in the Developer Tools is the important thing right now.

Notice that new items are periodically appearing in the Network tab.

These are the AJAX requests and responses. Some of them are images returned from the server, and some are data for use by the client‐side JavaScript.

4. Click on one of the rows in the Name column of the Networks tab. Additional data will be displayed about that particular item, as shown in Figure 16-5.

5. Click through the tabs (Headers, Preview, Response and so on) in the detailed data pane and examine the data.The first tab, Headers, displays the HTTP request that was sent to the remote server. Take a look in particular at the Request URL. This is a standard website address that passes data to a remote server.

6. Select and copy the value of the Request URL from one of the items you inspected.

7. Open a new tab in your browser and paste the entire Request URL into the address bar. A page containing data or an image opens, as in Figure 16-6.

Categories
JavaScript Tutorials

Introduction to AJAX and JSON

AJAX is a technique for making web pages more dynamic by sending and receiving data in the background while the user interacts with the pages. JSON has become the standard data format used by AJAX applications. In this chapter, you find out how to use AJAX techniques to make your site sparkle!

Working Behind the Scenes with AJAX

Asynchronous JavaScript + XML (AJAX) is a term that’s used to describe a method of using JavaScript, the DOM, HTML, and the XMLHttpRequest object together to refresh parts of a web page with live data without needing to refresh the entire page. AJAX was first implemented on a large scale by Google’s Gmail in 2004 and then was given its name by Jesse James Garret in 2005.

The HTML DOM changes the page dynamically. The important innovation that AJAX made was to use the XMLHttpRequest object to retrieve data from the server asynchronously (in the background) without blocking the execution of the rest of the JavaScript on the webpage.

Although AJAX originally relied on data formatted as XML (hence the X in the name), it’s much more common today for AJAX applications to use a data format called JavaScript Object Notation (JSON). Most people still call applications that get JSON data asynchronously from a server AJAX, but a more technically accurate (but less memorable) acronym would be AJAX.

AJAX examples

When web developers first started to use AJAX, it became one of the hallmarks of what was labeled Web 2.0. The most common way for web pages to show dynamic data prior to AJAX was by downloading a new web page from the server. For example, consider craigslist.org, shown in Figure 16-1.To navigate through the categories of listings or search results on Craigslist, you click links that cause the entire page to refresh and reveal the content ofthe page you requested. While still very common, refreshing the entire page to display new data in just part of the page is unnecessarily slow and can provide a less smooth user experience.

Compare the craigslist‐style navigation with the more application‐like navigation

of Google Plus, shown in Figure 16-2, which uses AJAX to load new content into part of the screen while the navigation bar remains static. In addition to making web page navigation smoother, AJAX is also great for creating live data elements in a web page. Prior to AJAX, if you wanted to display live data, a chart, or an up‐to‐date view of an email inbox, you either

needed to use a plug‐in (such as Adobe Flash) or periodically cause the web page to automatically refresh. With AJAX, it’s possible to periodically refresh data through an asynchronous process that runs in the background and then update only the elements of the page that need to be modified. See Chapter 10 to find out how to update the HTML and CSS of a web page using the HTML DOM’s methods and properties. AJAX relies on these same techniques to display web pages with updated data. Weather Underground’s Wundermap, shown in Figure 16-3, shows a weather map with constantly changing and updating data overlays. The data for the map is retrieved from remote servers using AJAX.

Categories
JavaScript Tutorials

Validating user input

One of the most common uses for JavaScript is to check, or validate, form input before submitting user input to the server. JavaScript form validation provides an extra safeguard against bad or potentially unsafe data making its way into a web application. It also provides users with instant feedback about whether they’ve made a mistake. Some of the most common JavaScript input validation tasks have been replaced by HTML attributes in HTML5. However, due to browser incompatibilities, it’s still a good practice to validate user-submitted data using JavaScript.

In the calculator program in Listing 12-4, the input type was set to number for the operand units. This should cause the browser to prevent the user from submitting non-numeric values into these fields. Because the number input type is relatively new, you can’t always count on the browsers to support it, so using JavaScript user input validation is important. Listing 12-5 demonstrates an input validation script. The important thing to notice here is that the action of the form has been set to the input validation function. The submit() method of the form runs only after the tests in the input validation function have finished. The line in the preceding code that does the real magic is this strange-looking 

one inside of the validate() function:

if (/^\d+$/.test(first) && /^\d+$/.test(second)) { ... }

The characters between / and / make up what’s called a regular expression. A regular expression is a search pattern made up of symbols that represent groups of other symbols. In this case, we’re using a regular expression to check whether the values the user entered are both numeric. You can find out more about regular expressions in Chapter 14.Input validation is such a common use for JavaScript that many different techniques have been created for doing it. Before you reinvent the wheel for your particular JavaScript application, do a search for “open source JavaScript input validation” and see whether any existing libraries of code can save you some time and give you more functionality.

Listing 12-5: Performing Input Validation with JavaScript

<html>
  <head>
    <title>Math Fun</title>
    <script>
      function registerEvents() {
        document.mathWiz.operate.addEventListener('click',validate);
      }
      function validate() {
        var first = document.mathWiz.numberOne.value;
        var second = document.mathWiz.numberTwo.value;
        var operator = document.mathWiz.operator.value;
        if (/^\d+$/.test(first) && /^\d+$/.test(second)) {
          doTheMath();
        }
        else {
          alert("Error: Both numbers must be numeric");
        }
      }
      function doTheMath() {
        var first = parseInt(document.mathWiz.numberOne.value);
        var second = parseInt(document.mathWiz.numberTwo.value);
        var operator = document.mathWiz.operator.value;
        switch (operator){
          case "add":
          var answer = first + second;
          break;
          case "subtract":
          var answer = first - second;
          break;
          case "multiply":
          var answer = first * second;
          break;
          case "divide":
          var answer = first / second;
          break;
        }
        document.mathWiz.theResult.value = answer;
      }
    </script>
  </head>
  <body onload="registerEvents();">
    <div id="formErrors"></div>
    <form name="mathWiz">
      <label>First Number: <input type="number" name="numberOne"></label><br>
      <label>Second Number: <input type="number" name="numberTwo"></label><br>
      <label>Operator:
        <select name="operator">
          <option value="add"> + </option>
          <option value="subtract"> ‐ </option>
          <option value="multiply"> * </option>
          <option value="divide"> / </option>
        </select>
      </label><br>
      <input type="button" name="operate" value="Do the Math!"><br>
      <label>Result: <input type="number" name="theResult"></label>
    </form>
  </body>
</html>
Categories
JavaScript Tutorials

Working with the Form Object

The HTML DOM represents forms using the Form object. Through the Form object, you can get and set values of form fields, control the action that’s taken when a user submits a form, and change the behavior of the form.

Using Form properties

The properties of the Form object match up with the attributes of the HTML form element (see the section earlier in this chapter). They’re used for getting or setting the values of the HTML form element attributes with JavaScript. Table 12-2 lists all the properties of the Form object. DOM objects are representations of HTML pages. Their purpose is to give you access (also known as programming interface) to the different parts of the document through JavaScript. Anything within an HTML document can be accessed and changed with JavaScript by using the DOM.

You can find techniques for setting or getting the value of a form’s properties in Chapter 10. After referencing the form using one of these methods, you then access the property using dot notation or the square bracket method.To get the value of the name property of the first form in a document, you could use the following statement:

document.getElementByTagName("form")[0].name

A more common way to access a form is by assigning it an id attribute and using getElementById to select it.

The DOM provides another, more convenient method for accessing forms, the forms collection. The forms collection lets you access the forms in a document in two different ways:

  • By index number: When a form element is created in the document, it is assigned an index number, starting with zero. To access the first form in the document, use document.forms[0].
  • By name: You can also access forms using the value of the name attribute of the form element. For example, to get the value of the action property of a form with a name of “subscribeForm”, you would use document.forms.subscribeForm.action. Or you can use the square brackets method of accessing properties and write document.forms[“subscribeForm”].action.

Using the Form object’s methods

Let’s go through two of the form object’s methods: reset() and submit().

The reset() method

The reset() method clears any changes to the form’s fields that were made after the page loaded and resets the default values. It does the same thing as the HTML reset button, which is created by using a type=”reset” attribute with an input element, as shown in the following code:

<input type="reset" value="Clear the form">

The submit() method

The submit() method causes the form to submit its values according to the properties of the form (action, method, target, and so on). It does the same thing as the HTML submit button, which is created by using a type=”submit” attribute with an input element, as shown in the following code:

<input type="submit" value="Submit the form">

Listing 12-3 demonstrates the use of the submit() and reset() methods along with several of the form object’s properties.

Accessing form elements

JavaScript offers several different ways to access form input fields and their values. These ways are not all created equal, however, and differences of opinion exist among JavaScript programmers as to which technique is the best. The following list presents the different techniques and their benefits and drawbacks:

  • Use the index number of the form and of its input fields. For example,to access the first input field in the first form, you could use document.forms[0].elements[0]. Avoid the preceding technique because it relies on the structure of the document and the order of the elements within the form not to change. As soon as someone decides that the email field should come before the first name field in the form, your whole script will break.
  • Use the name of the form and the name of the input field. For example: document.myForm.firstName. This technique has the benefit of being easy to read and easy to use. It’s supported by every browser (and has been since very early in the development of the DOM).
  • Use getElementById to select the form and the name of the input field to select the input. For example: document.getElementById(“myForm”).firstName. This technique requires you to assign an id attribute to the form of the element. For example, the preceding code would match an input field named firstName inside of the following form element.
<form id="myForm" action="myaction.php">
  . . .
</form>

Use a unique id attribute value on the field to access the field directly. For example: document.getElementById(“firstName”). Something to remember when using the preceding technique is that if you have multiple forms on your page, you need to make sure that each form field has a unique id attribute (id attribute values must be unique anyway, so it’s not really an issue).

Getting and setting form element values

The DOM gives you access to form elements’ names and values using the name and value properties.

Listing 12-4 demonstrates the getting and setting of form input fields using a simple calculator application.

Listing 12-4: A Calculator App Demonstrating the Getting and Setting of Form Input Fields:

Examples

Create a form using input fields along with submit and reset buttons.

Categories
JavaScript Tutorials

Understanding HTML Forms

Handling user input and sending back results are basic and necessary functions for any computer program. In this topic, you will find out how JavaScript and HTML can work together to receive and output data.

The primary way to get input from users of web applications is through HTML forms. HTML forms give web developers the ability to create text fields, drop‐down selectors, radio buttons, checkboxes, and buttons. With CSS, you can adjust the look of a form to fit your particular website. JavaScript gives you the ability to enhance the functionality of your form.

The form element

All HTML forms are contained within a form element. The form element is the container that holds the input fields, buttons, checkboxes and labels that make up a user input area. The form element acts much like any container element,such as a div, article, or section. But it also contains some attributes that tell the browser what to do with the user input from the form fields it contains.

The code below shows an HTML form containing two input fields and a submit button.

<html>
  <head>
    <title>HTML form</title>
  </head>
  <body>
    <form action="subscribe.php" name="newsletterSubscribe" method="post">
      <label for="firstName">First Name: </label>
      <input type="text" name="firstName" id="firstName" /><br />
      <label for="email">Email: </label>
      <input type="text" name="email" id="email" /><br />
      <input type="submit" value="Subscribe" />
    </form>
  </body>
</html>

In the preceding example, the form element has three attributes:

  • action: Tells the browser what to do with the user input. Often, the action is a server-side script.
  • name: Specifies the name that the programmer assigned to this form. The name attribute of the form is useful for accessing the form using the DOM.
  • method: Takes a value of either get or post, indicating whether the browser should send the data from the form in the URL or in the HTTP header.

In addition to these three attributes, the form element can also contain several other attributes:

  • accept-charset: Indicates the character sets that the server accepts. Unless you’re working with multilingual content (and even then), you can safely leave this attribute out.
  • autocomplete: Indicates whether the input elements of the form should use autocomplete in the browser.
  • enctype: Indicates the type of content that the form should submit to the server. For forms that are submitting only text data to the server, this should be set to text/html. If your form is submitting a file to the server (such as an uploaded graphic), the enctype should be multipart/form-data. The default value is application/x-www-form-urlencoded.
  • novalidate: A Boolean value indicating whether the input from the form should be validated by the browser on submit. If this attribute isn’t specified, forms are validated by default.
  • target: Indicates where the response from the server should be displayed after the form is submitted. The default (“_self”) is to open the response in the same browser window where the form was. Another option is to open the response in a new window (“_blank”).

The label element

You can use the label element to associate an input field’s description (label) with the input field. The for attribute of the label element takes the value of the id attribute of the element that the label should be associated with, as shown in this example:

<label for="firstName">First Name: </label>
<input type="text" name="firstName">

Another method for associating a label with a form field is to nest the form field within the label element, as shown in this example:

<label>First Name: <input type="text" name="firstName"></label>

This method has the advantage of not requiring the input field to have an id (which is often just a duplicate of its name attribute).

The input element

The HTML input element is the most fundamental form-related HTML element. Depending on the value of its type attribute, it causes the browser to display (or not display) several types of input fields.Most commonly, the input element’s type is set to “text”, which creates a text input in the browser. The optional value attribute assigns a default value to the element, and the name attribute is the name that is paired with the value to form the name/value pair that can be accessed through the DOM and that is submitted along with the rest of the form values when the form is submitted.

A basic text input field looks like this:

<input type="text" name="streetAddress">

With HTML5, the input element gained a bunch of new possible type attribute values. These new values allow the web developer to more precisely specify the type of value that should be provided in the input. They also allow the web browser to provide controls that are better suited to the type of input that’s required to do input validation and results in better web applications. It may seem odd that this chapter focuses so much on the form capabilities of HTML, rather than jumping right into JavaScript. However, forms are an area where HTML can really reduce the workload of programmers, so it’s vital that JavaScript programmers learn what can be accomplished with forms through HTML.

The input element’s possible values for the type attribute are shown in Table 12-1.

The select element

The HTML select element defines either a drop-down or a multiselect input. The select element contains option elements that are the choices that the user will have in the select control, as shown in Listing 12-2.

Listing 12-2: A Drop-Down Form Control, Created Using the select Element

<select name="favoriteColor"><option value="red">red</option>
  <option value="blue">blue</option><option value="green">green<option>
</select>

The form created by the markup in Listing 12-2 is shown in Figure 12-2.

The textarea element

The textarea element defines a multiline text input field:

<textarea name="description" rows="4" cols="30"></textarea>

The button element

The button element defines another way to create a clickable button:

<button name="myButton">Click The Button</button>

The button element can be used in place of input elements with the type attribute set to ‘submit’. Or, you can use button elements anywhere you need a button, but where you don’t want the submit action to happen. If you don’t want the button to submit the form when clicked, you need to add a type attribute to it with the value of ‘button’.

Examples

Create a user registration form consisting of firstname, lastname, age, email and password using text fields.

<html>
  <head>
  </head>
  <body>
    <form>
      <label>Firstname: </label>
      <input type="text" /><br><br>
      <label>Lastname: </label>
      <input type="text" /><br><br>
      <label>Age: </label>
      <input type="text" /><br><br>
      <label>Email: </label>
      <input type="text" /><br><br>
      <label>Password: </label>
      <input type="text" />
    </form>
  </body>
</html>

Create a student registration form consisting of fullname, age, gender, courses, email and password using text fields, select box, checkbox, and password fields.

<html>
  <head>
  </head>
  <body>
    <form>
      <label>Fullname: </label>
      <input type="text" /><br><br>
      <label>Age: </label>
      <input type="text" /><br><br>
      <label>Gender: </label>
      <select>
        <option>Male</option>
        <option>Female</option>
        <option>Others</option>
      </select><br><br>
      <label>Courses: </label><br>
      <input type="checkbox" />HTML<br>
      <input type="checkbox" />CSS<br>
      <input type="checkbox" />JavaScript<br>
      <input type="checkbox" />Node.js<br><br>
      <label>Email: </label>
      <input type="text" /><br><br>
      <label>Password: </label>
      <input type="password" />
    </form>
  </body>
</html>

Create a feedback form consisting of fullname, email and feedback using text fields and textarea fields.

<html>
  <head>
  </head>
  <body>
    <form>
      <label>Fullname: </label>
      <input type="text" /><br><br>
      <label>Email: </label>
      <input type="text" /><br><br>
      <label>Feedback: </label><br>
      <textarea rows="5" cols="50"></textarea>
    </form>
  </body>
</html>