Categories
JavaScript JavaScript Basics

Adding Inputs and Outputs to JavaScript Apps

Spread the love

For many web apps, inputs and outputs are important parts of the app. Many parts of most applications consist of forms. JavaScript makes it easy to add forms and handle inputs and then get the outputs. An HTML form consists of many parts. It can have text inputs, text areas, checkboxes, radio buttons, dropdowns, buttons, etc. The look of them can be adjusted with CSS, and JavaScript lets you add dynamic functionality to the form.

The form element is the HTML element that contains the controls for forms. It holds all the text inputs, radio buttons, checkboxes, text areas, etc., along with the label text for each element. It can also contains HTML elements that divide the form into sections like div , article , and section elements.

To make a simple form, we can write the following:

<html>  
  <head>  
    <title>Form</title>  
  </head>  
  <body>  
    <form action="save.php" name="nameForm" method="post">  
      <label for="firstName">First Name: </label>  
      <input type="text" name="firstName" id="firstName" /><br />  
      <label for="lastName">Last Name: </label>  
      <input type="text" name="lastName" id="lastName" /><br />  
      <input type="submit" value="Submit" />  
    </form>  
  </body>  
</html>

In the example above, we have the action attribute in the form tag to tell the browser what to do with the form when the submit action is triggered. It can be sent to the server-side directly, or it can be manipulated on the client-side first before sending it to the server via Ajax. The name attribute is the name that the programmer assigns to the form. It’s a handy reference for accessing it in our JavaScript code. The method attribute is used when we send the form data to the server directly and it’s used to specify the HTTP method used to send the data to the server.

Other attributes that form elements can have include:

  • accept-charset: specifies the character set to use when sending the data to the server. It’s useful if your form inputs have multilingual content.
  • autocomplete: specifies whether the form should use browser’s autocomplete
  • enctype: indicates the type of content that’s sent to the server. If the data sent to the server is all text, then it should be text/html. If the form has file inputs, then it should be multipart/form-data. The default value is application/x-www-form-urlencoded .
  • novalidate: a boolean value that specifies whether we want to use browser’s form validation for form inputs
  • target: specifies whether we want the server’s response should be displayed after the form is submitted. The default setting is to open the response in the same browser window (value is _self ). If you want the response data to be shown in a new window, then it should be set to _blank.

Label Element

The label element is used to specify the text associated with a form field. It makes it clear to the user which field is used for entering what kind of data. It has a for attribute that takes the id of the input element as the value to associate the label with the form field. You can also nest the form field in the label element to associate the form field with the input element, so you don’t have to have an id attribute in your input field.

Input Element

Almost all forms have an input element. It’s used for entering text. Input elements have the type attribute which is usually set to text as the value. Other possible values include number , email , password , etc. The full list of types are listed below. Inputs also can have a value attribute which lets us set the value entered into the form field. It’s handy if you want to preset the value of the form field. The name attribute is also an important one since it lets us get the input by name and get the value from it.

Below is the full list of possible inputs that we can set in the type attribute:

  • button — a clickable button
  • checkbox — checkbox
  • color — color picker
  • date — date control
  • datetime — control to let us enter date and time (year, month, day, hour, minute, second, and a fraction of a second in UTC)
  • datetime-local — control to let us enter date and time (year, month, day, hour, minute, second, and a fraction of a second in local time)
  • email — email address
  • file — file upload
  • hidden — hidden input
  • image — submit button that has an image instead of text
  • month — month and year picker
  • number — input that only takes numbers
  • password — password field
  • radio — radio button
  • range — input that takes a range of numbers
  • reset — reset button
  • search — input that takes a search string
  • submit — submit button
  • tel — phone number input
  • text — a single line of text input. This is the default choice.
  • time — time input without taking into account the time zone
  • url — URL input
  • week — week and year input without taking into account the time zone

Select Element

The select element is a drop-down that lets users select from one or more choices in the drop-down list. We can also have default choices with the selected attribute and group the drop-down options with optgroup.

A simple example would be:

<select name='color'>  
  <option color='white'>White</option>  
  <option color='yellow'>Yellow</option>  
  <option color='black'>Black</option>  
</select>

If we want to group items together we can write:

<select name='car'>  
  <optgroup label="American Cars">  
    <option value="ford">Ford</option>  
    <option value="gm">GM</option>  
  </optgroup>  
  <optgroup label="Japanese Cars">  
    <option value="toyota">Toyota</option>  
    <option value="mazda">Mazda</option>  
  </optgroup>  
</select>

An option can have a selected attribute to make a choice a preset choice:

<select name='color'>  
  <option color='white' selected>White</option>  
  <option color='yellow'>Yellow</option>  
  <option color='black'>Black</option>  
</select>

Textarea

A textarea element is a multline text input field:

<textarea name='recipe' rows='10' cols='50'></textarea>

Button

We can use the button element to create our submit button instead of an input with type attribute set to submit . We can write:

<button type='submit'>Submit</button>

which is the same as:

<input type='submit value='Submit' >

The Form Object

The form object is an HTML DOM object that represents the form element that you defined in HTML. We can manipulate the form object to get the input and set different options to our liking, to change the behavior of the form. With the form object, we get full access to all parts of the form.

A form object has the following properties:

  • acceptCharset — get or set a list of character sets supported by the server
  • action — get or set the action attribute of the form
  • autocomplete — get or set whether to turn on or off autocomplete attribute of the form
  • encoding — set the enctype attribute of the form, or the way data is encoding when sending to the server
  • enctype — set the enctype attribute of the form, or the way data is encoding when sending to the server
  • length — get the number of controls in a form
  • method — get or set the HTTP method used to submit the form data
  • name — get or set the name attribute of the form
  • noValidate — get or set the novalidate attribute of the form, or whether validation can be skipped by the browser
  • target — indicate the place to show the response data after submitting a form

Autocomplete Attribute

The autocomplete attribute in a form tells the browser whether to use its autocomplete feature to let users enter data by getting existing input data that was saved from previous data entries. We can set it to form the whole form or just single inputs.

Getting Form and Input Attributes

We can get a form’s attribute like getting the attributes of any other element. So we can use getElementById , getElementsByTagName , querySelector , querySelectorAll , or getElementsByClassName to get what we want.

For example, we can use document.querySelector('form') to get the first element with the form tag, which is a convenient way of getting forms. If we have more than one form element in one page, then we can get it by using document.querySelector('form')[0] to get the first one, document.querySelector('form')[1] to get the second one, etc.

Also, there is the document.forms property, which we can use to access a form if the form has a name attribute. If it has a name attribute, then we can pass it in as the key. For example, if there’s a form with name attribute set to nameForm , then we can write document.forms.nameForm or document.forms['nameForm'] to get the form.

A form object has a methods, reset() and submit() . The reset method clears the input values and reset all validation previously done to the form. It’s the same as having a input with type reset in the form, which also clears the form’s inputs, like the following:

<input type='reset' value='Clear form'>

The submit method submits the form data to the place you want depending on the action, method and target attributes. It’s the same as what an input element with type submit does, like the following:

<input type='submit' value='Submit'>

We have the example below for making a form that displays an alert of the inputted values after the Submit button is clicked. In index.html, we add our form by adding the following:

<html>  
  <head>  
    <title>Form</title>  
  </head>  
  <body>  
    <form action="" name="nameForm" method="post">  
      <label for="firstName">First Name: </label>  
      <input type="text" name="firstName" id="firstName" /><br />  
      <label for="lastName">Last Name: </label>  
      <input type="text" name="lastName" id="lastName" /><br />  
      <input type="submit" value="Submit" />  
    </form>  
    <script src="script.js"></script>  
  </body>  
</html>

Then in script.js , we add:

window.onload = () => {  
  const nameForm = document.forms.nameForm;  
  nameForm.method = "post";  
  nameForm.target = "_blank";  
  nameForm.action = "";  
  nameForm.addEventListener("submit", e => {  
    e.preventDefault();  
    const firstName = document.getElementById("firstName");  
    const lastName = document.getElementById("lastName");  
    alert(`Your name is ${firstName.value} ${lastName.value}`);  
  });  
};

We use the document.forms property to get the form with name attribute set to nameForm in the script. Then we set the method , target , and action properties. We do not want to submit to a server immediately, so in the handler function that we pass into the addEventListener function, we add e.preventDefault() to prevent the submit action. Then we get the values of the firstName and lastName field and display an alert from it.

Other ways to get input fields in a form element in this example is to use nameForm.firstName instead of document.getElementById(“firstName”), or set an ID for the form and then get the form element by ID then access the form field with the given name as a property of the form object. So if we have:

<html>  
  <head>  
    <title>Form</title>  
  </head>  
  <body>  
    <form action="" name="nameForm" id="nameForm" method="post">  
      <label for="firstName">First Name: </label>  
      <input type="text" name="firstName" id="firstName" /><br />  
      <label for="lastName">Last Name: </label>  
      <input type="text" name="lastName" id="lastName" /><br />  
      <input type="submit" value="Submit" />  
    </form>  
    <script src="script.js"></script>  
  </body>  
</html>

in index.html , then in script.js , we can write:

document.getElementById("nameForm").firstName

to get the first name field instead of what we have above.

Setting Form Values

We can set form values with the value property of an input element. We can access the form elements like we did before, and set the value attribute of a form element. For example, if we have index.html with the following code:

<html>  
  <head>  
    <title>Form</title>  
  </head>  
  <body>  
    <form action="" name="nameForm" id="nameForm" method="post">  
      <label for="firstName">First Name: </label>  
      <input type="text" name="firstName" id="firstName" /><br />  
      <label for="lastName">Last Name: </label>  
      <input type="text" name="lastName" id="lastName" /><br />  
      <input type="submit" value="Submit" />  
    </form>  
    <script src="script.js"></script>  
  </body>  
</html>

and script.js with:

window.onload = () => {  
  const nameForm = document.forms.nameForm;  
  nameForm.method = "post";  
  nameForm.target = "_blank";  
  nameForm.action = "";  
  const firstName = document.getElementById("firstName");  
  const lastName = document.getElementById("lastName");  
  firstName.value = "John";  
  lastName.value = "Smith"; nameForm.addEventListener("submit", e => {  
    e.preventDefault();  
    alert(`Your name is ${firstName.value} ${lastName.value}`);  
  });  
};

Then we set the default value of firstName and lastName fields by setting the value property of both field objects when the page is loaded.

Form Validation

Most forms need to be validated for valid data before submitting the form data to ensure that we don’t get bad data. With JavaScript, we can use regular expressions to validate the content of each input to ensure that they’re entered in the correct format. We can extend the examples above to include form validation. HTML5 also provides attributes to validate form data in HTML instead of JavaScript. However, if you want to customize your validation, then JavaScript makes this possible.

To validate forms with JavaScript, we can do the following. In index.html, we put:

<html>  
  <head>  
    <title>Form</title>  
  </head>  
  <body>  
    <form action="" name="nameForm" id="nameForm" method="post">  
      <label for="firstName">First Name: </label>  
      <input type="text" name="firstName" id="firstName" /><br />  
      <label for="lastName">Last Name: </label>  
      <input type="text" name="lastName" id="lastName" /><br />  
      <label for="email">Email: </label>  
      <input type="text" name="email" id="email" /><br />  
      <input type="submit" value="Submit" />  
    </form>  
    <script src="script.js"></script>  
  </body>  
</html>

Then in script.js , we add:

window.onload = () => {  
  const nameForm = document.forms.nameForm;  
  nameForm.method = "post";  
  nameForm.target = "\_blank";  
  nameForm.action = "";  
  nameForm.addEventListener("submit", e => {  
    e.preventDefault();  
    const firstName = document.getElementById("firstName");  
    const lastName = document.getElementById("lastName");  
    const email = document.getElementById("email");  
    let errors = [];  
    if (!firstName.value) {  
      errors.push("First name is required.");  
    } 

    if (!lastName.value) {  
      errors.push("Last name is required.");  
    } 

    if (!email.value) {  
      errors.push("Email is required.");  
    } 

    if (!/\[^@\]+@\[^\.\]+\..+/.test(email.value)) {  
      errors.push("Email is invalid.");  
    } 

    if (errors.length > 0) {  
      alert(errors.join(" "));  
      return;  
    }  
    alert(  
      `Your name is ${firstName.value} ${lastName.value}. Your email is ${email.value}`  
    );  
  });  
};

In the example above, we check each field’s value to see if they’re filled in. Then for the email field, we check if the field is filled in and that it matches the email format with a regular expression check. To learn more about regular expressions, you can go to https://regexone.com/. The regular expression we have basically checks if we have characters before the at sign, then the at sign, then check if we have anything separated by a dot after the at sign.

If there are errors, we display an alert box with all the errors. Otherwise, we show what’s entered.

If we want to use HTML for validation, we can do the following instead. In index.html, we put:

<html>  
  <head>  
    <title>Form</title>  
  </head>  
  <body>  
    <form action="" name="nameForm" id="nameForm" method="post">  
      <label for="firstName">First Name: </label>  
      <input type="text" name="firstName" id="firstName" required /><br />  
      <label for="lastName">Last Name: </label>  
      <input type="text" name="lastName" id="lastName" required /><br />  
      <label for="email">Email: </label>  
      <input type="text" name="email" id="email" /><br />  
      <input type="submit" value="Submit" />  
    </form>  
    <script src="script.js"></script>  
  </body>  
</html>

Then in script.js , we put:

window.onload = () => {  
  const nameForm = document.forms.nameForm;  
  nameForm.method = "post";  
  nameForm.target = "_blank";  
  nameForm.action = "";  
  nameForm.addEventListener("submit", e => {  
    e.preventDefault();  
    const firstName = document.getElementById("firstName");  
    const lastName = document.getElementById("lastName");  
    const email = document.getElementById("email");  
    alert(  
      `Your name is ${firstName.value} ${lastName.value}. Your email is ${email.value}`  
    );  
  });  
};

We’ve put validation attributes in the input elements like required and pattern in the HTML form instead of using JavaScript to validate the data. They serve the same purpose since the browser prevents you from submitting the form if there’re invalid values in any input, so the submit event is only triggered if everything’s valid. The only difference is that the validation messages are controlled by the browser so there’s less choice in controlling how it’s displayed.

Now that we know how to add forms to a web page with form validation, we can make many features of a web app. For many web apps, inputs and outputs are important parts of the app. Many parts of most applications consist of forms.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.