Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Access HTML Form Elements in JavaScript

As with any other HTML elements, you can interact directly with HTML5 elements in JavaScript. The trick is to ensure that the elements you choose will work with the browsers and platforms you need to support.

In this example, you see how to use the <figure> and <figcaption> tags as part of a solution that loads an image from disk and stores it in an <img> tag. The following code shows the HTML you use to perform the task.

<figure onclick="Clicked()">
  <img id="Image"
    src=""
    alt=""
    height="200px"
    width="200px">
  <figcaption id="Caption" />
</figure>

The <figure> tag acts as a container that holds the <img> and <figcaption> tags. The use of a container like this means that you can perform tasks such as formatting both image and caption at the same time.

Events are also handled jointly. In this case, it doesn’t matter whether the user clicks the image or the caption, the application calls Clicked(). In this case, all that Clicked() does is display a message to the user as shown here:

function Clicked()
{
  // Display a message.
  alert("You clicked the image.");
}

JavaScript is fully capable of accessing these elements. In this case, the <img> tag is empty when the form loads. Clicking a button displays the image onscreen by changing the <img> tag content. Here’s the code needed to load the image:

function LoadImage()
{
  // Specify the image.
  var Image = document.getElementById("Image");
  Image.alt = "This is a test image.";
  Image.src = "TestImage.png";
 
  // Set the caption.
  var Caption = document.getElementById("Caption");
  Caption.innerHTML = "A Test Image";
}

When working with the <img> tag, you access the src (image source) and alt (image alternative text description) attributes directly. Set the <figcaption> content using the innerHTML property.

image0.jpg
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!