JavaScript For Kids For Dummies
Book image
Explore Book Buy On Amazon

The most common way to get user input for a JavaScript program is by using HTML form elements. The latest version of HTML, HTML5, has several new form elements and attributes.

Text inputs

Text inputs are the most basic type of HTML form field. They’re used for giving the website user a blank input where she can enter any value. Here’s an example of the code used to create a text input:

Here’s what this field looks like in a browser:

image0.jpg

Placeholder text

Placeholder text appears inside the input field before a user starts typing. It’s useful for telling the user what you expect them to enter.

Here’s an example of using placeholder text in a text input:

Here’s what this field looks like in a web browser.

image1.jpg

Autofocus

When the input field is selected and you can see your cursor inside of it, it “has focus.” If you want a certain field (such as the First Name field) to have “focus” as soon as a web page loads, you can use the autofocus attribute. Here’s what it looks like:

Email input

The email input field looks like a text box input and it works just like a text input field in most cases, too. But, sometimes, the web browser treats the email input field differently from a text input field. For example, when an email input field is “in focus” on an iPhone, a special keyboard displays that features shortcuts for entering email addresses.

Here’s an example of using the email input field:

Slider input

A slider input is an input field that allows the user to select a number within a range of numbers, by using a drag-and-drop control.

Here’s the code for creating a slider:

Here’s what a slider looks like in a web browser.

image2.jpg

Required

If you want force your user to enter a value into a field before he’s able to submit the form, HTML5 has an attribute called required.

To make a form field required, you just need to add the new attribute within a form input field, like this:

When a user tries to submit this form without filling in the phoneNumber field, she gets a message asking her to fill it in:

image3.jpg

As of this writing, not all web browsers support the required attribute, but it is supported by Chrome, Firefox, Internet Explorer, and Opera.

Finding out more

For more information about the elements and attributes and how to work with them in JavaScript, visit the HTML forms guide at Mozilla Developer Network.

About This Article

This article is from the book:

About the book authors:

Chris Minnick and Eva Holland are experienced web developers, tech trainers, and coauthors of Coding with JavaScript For Dummies. Together they founded WatzThis?, a company focused on training and course development.

This article can be found in the category: