Processing Forms

Soon you will learn how to upload the information that users enter into form elements to a server. That will be a great day. Not all form data needs to go to a server, however. Some tasks can be completed without ever leaving the browser. You process form input on the client using JavaScript.

Consider the task of creating a binary number converter. You want the viewer to be able to convert a decimal number into binary and vice versa. Two input elements should be sufficient, you think, so you create this interface in HTML:

html
js
preview

There's no input element for binary numbers like there is for decimal numbers, so you decide to use just plain text inputs for both. You consider putting and buttons in the HTML, but you think it'd be more humane to perform the conversion automatically as the viewer types. Automatic processing is sometimes more humane, and sometimes it is not. If the processing is slow or if you bombard the viewer with premature error messages, then non-automatic processing triggered by a button is more humane. In this case, automated processing is probably fine.

Input elements fire an input event whenever their content is modified. You wire a listener to this event for the decimal input and log the element's value:

html
js
preview

Open this example as a popup and try typing in the decimal box. Do you see the log messages?

Form elements yield up their values as strings. You use the parseInt function to turn the input into a number, convert it to a binary string using toString, and update the value of the binary input:

html
js
preview

Try entering a decimal number. Does the binary representation appear automatically? Do you encounter any errors?

When you delete the decimal input entirely, NaN (not-a-number) appears in the binary input. That's what you get for parsing the empty string. You add a conditional statement to prevent this:

html
js
preview

Converting from binary to decimal is completed similarly:

html
js
preview

Try converting in both directions. Can you break the conversion?

Because the input elements are text inputs, the viewer may enter any text, not just binary or decimal numbers. You decide to indicate bad input by changing the background color of the offending input. You add a stylesheet and check the validity of the input using a couple of regular expressions:

html
css
js
preview

Try adding the bad-input class when the data is invalid. What must you do to recover after bad input has been entered?