If Statements: Clearing Form Fields

Free JavaScript & jQuery Tutorial

Delve into this comprehensive tutorial on leveraging JavaScript & jQuery to create interactive web forms with conditional statements, event handlers, and embedded scripts.

This exercise is excerpted from Noble Desktop’s past JavaScript training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this JavaScript & jQuery tutorial:

Using if statements, Adding event handlers, Placing JavaScript in an HTML document

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Exercise Preview

form fields

Exercise Overview

There are times when you only want your JavaScript code to be executed if certain criteria have been met. We can test for those criteria, and then execute code if the criteria are true. These are called conditional statements. In this exercise, we’d like to include placeholder text in our form fields. Users shouldn’t have to delete the placeholder to enter text into the form field. We’ll detect whether the form field has text in it (or not) and have our JavaScript respond appropriately.

Getting Started

  1. Open your code editor if it isn’t already open.
  2. Close any files you may have open.
  3. For this exercise we’ll be working with the Form-Fields folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. You may want to open that folder in your code editor if it allows you to (like Visual Studio Code does).
  4. Open form.html from the Form-Fields.
  5. Preview the page in a browser. This is the same page you worked with in the previous exercise.
  6. Leave the page open in the browser so we can come back to it later.
  7. Switch back to your code editor.
  8. We want to clear the initial text from the Name text field when the user clicks or Tabs into it. We’ll need a function to make sure it doesn’t happen on page load. Let’s first call that function by adding an event handler.

    Add the following bold code to the nameField input tag on line 25:

    <input id="nameField" name="nameField" type="text" class="textfield" value="First and Last Name" onfocus="clearName();">
    

    NOTE: onfocus is similar to onclick, but is better in this case. onclick would only work if the user clicks with a mouse. onfocus works when the object becomes focused on (or highlighted). That means it’s triggered by mouse clicks as well as users Tabbing into the field via the keyboard.

  9. Now let’s define that function. Add the following bold code before the </head> tag (on line 8):

    <link rel="stylesheet" href="css/main.css">
    <script>
    
    </script>
    </head>
    
  10. We already told our HTML to listen for an onfocus event and trigger a clearName() function at that time. Now, we’ll create the function that will be triggered.

    In the script tag, add the following bold code:

    <script>
       function clearName() {
    
       }
    </script>
    
  11. We saw in the previous exercise that we can successfully talk to the text field, and get and set input values using JavaScript. We’ll use the same getElementById() method. Add the following bold code.

    function clearName() {
       document.getElementById('nameField').value = '';
    }
    

    At the end of the line we have a pair of single quotes with nothing between the quotes. That means the text field’s text will be set to nothing.

  12. Save and reload form.html in Chrome.

  13. Click into the Name field (or Tab into it). The default text should disappear.

  14. Type your name into the Name field and then click (or Tab) into the Phone field.

  15. Click (or Tab) back into the Name field to change the name. Whoops, the text disappeared again. What if someone makes a typo they need to correct? They’d have to retype the whole thing. How annoying! Let’s fix that.

Using If Statements

We need to add a conditional statement, which is a bit of logic that will only execute some code if a specific condition is met.

  1. Switch back to your code editor.

  2. The text should only be cleared if it says the default First and Last Name. Wrap the line into an if statement, and don’t miss the end curly bracket!

    function clearName() {
       if () {
          document.getElementById('nameField').value = '';
       }
    }
    
  3. Copy and paste the nameField line without the semi-colon into the if statement’s parentheses, as shown in bold below.

    function clearName() {
       if (document.getElementById('nameField').value = '') {
          document.getElementById('nameField').value = '';
       }
    }
    
  4. Change the if statement’s equal sign to a double equal sign as follows. One equal sign sets something equal to something else (so a change is happening). Two equal signs check to see if the values on either side of the == are already equal. It’s a test that returns true or false.

    if (document.getElementById('nameField').value == '') {
    
  5. In the nameField input tag around line 31, copy the value First and Last Name.

  6. Paste it into the if statement:

    if (document.getElementById('nameField').value == 'First and Last Name') {
    

    NOTE: We highly recommend copying and pasting things like this because even the best of us make typos. A simple typo can produce unexpected errors, making you waste a lot of time trying to figure out what’s wrong with a script. Copy/Paste can help you avoid that!

  7. Save the file, switch to the browser, and reload form.html.

  8. Type your name into the Name field.

  9. Click out and back into the Name field. It doesn’t disappear any more. That’s because we only clear the value if the value is equal to the initial text. Perfect.

  10. Switch back to your code editor.

  11. We want a similar function for the phone number, so let’s just duplicate the clearName() function and make a few corrections. Select and copy the entire clearName() function, including its ending curly braces.

    function clearName() {
       if (document.getElementById('nameField').value == 'First and Last Name') {
          document.getElementById('nameField').value = '';
       }
    }
    
  12. Paste a copy directly below it.

  13. Edit the code you pasted, changing name to phone in three places as shown below in bold. Pay close attention to capitalization!

    function clearPhone() {
       if (document.getElementById('phone Field').value == 'First and Last Name') {
          document.getElementById('phone Field').value = '';
       }
    }
    
  14. In the phoneField input around line 39, copy the value example: 212-123-1234.

  15. Paste it into the clearPhone if statement:

    if (document.getElementById('phoneField').value == 'example: 212-123-1234') {
    
  16. Add the onfocus call to the phoneField around line 39:

      <label for="phoneField">Phone:</label>
      <input id="phoneField" name="phoneField" type="text" class="textfield" 
       value="example: 212-123-1234" onfocus="clearPhone();">
    
  17. Save the file, switch to the browser, and reload form.html.

  18. Test out the two fields. They will only clear when they have the default values.

Reshowing Text Hints in Empty Form Fields

Currently, when we click into a field, JavaScript removes the text. That’s nice, but if the user clicks into another field without entering any text, it would be nice if the initial text would reappear.

  1. Switch back to your code editor.

  2. Select and copy the entire clearName() function around line 9 shown below:

    function clearName() {
       if (document.getElementById('nameField').value == 'First and Last Name') {
          document.getElementById('nameField').value = '';
       }
    }
    
  3. Paste a copy directly below the one you just copied.

  4. In the bottom copy you just pasted, change clearName to resetName as shown:

    function resetName() {
    
  5. If the text field is empty when the user clicks or Tabs out of it, we want to reset it back to the initial text. In the resetName() function, cut the First and Last Name from the if line and paste it into the line below, so you end up with:

    function resetName() {
       if (document.getElementById('nameField').value == '') {
          document.getElementById('nameField').value = 'First and Last Name';
       }
    }
    
  6. Next we must call our new function. Add the following to the nameField (around line 41):

    <input id="nameField" name="nameField" type="text" class="textfield" value="First and Last Name" onfocus="clearName()" onblur="resetName();">
    

    NOTE: onblur is the opposite of onfocus. onfocus is when the cursor is put into the text field, so onblur is when the cursor is removed from the text field (such as when the user clicks or Tabs into the next field).

  7. Save the file, switch to the browser, and reload form.html.

  8. Click or Tab into the Name field to see the text disappears. Then click or Tab into the Phone field and see the initial text reappear in the Name field. Great!

  9. Switch back to your code editor.

  10. Select and copy the entire clearPhone() function shown below:

    function clearPhone() {
      if (document.getElementById('phoneField').value == 'example: 212-123-1234') {
         document.getElementById('phoneField').value = '';
      }
    }
    
  11. Paste a copy directly below the one you just copied.

  12. In the bottom one you just pasted, change clearPhone to resetPhone as shown:

    function resetPhone() {
    
  13. In the resetPhone() function, cut the example: 212-123-1234 from the if line and paste it into the line below, so you end up with the code shown below:

    function resetPhone() {
       if (document.getElementById('phoneField').value == '') {
          document.getElementById('phoneField').value = 'example: 212-123-1234';
       }
    }
    
  14. Next we must call our new function. Add the following to the phoneField around line 49:

    <input id="phoneField" name="phoneField" type="text" class="textfield" value="example: 212-123-1234" onfocus="clearPhone()" onblur="resetPhone();">
    
  15. Save the file, switch to the browser, and reload form.html.
  16. Click or Tab between the Name and Phone fields. Their initial text should disappear when the cursor is there but reappear when you click to the next field. But if you type a name or phone number, that will remain instead of the initial text hint.

    NOTE: If you want to refer to our final code example, go to Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Form-Fields.

    HTML5 Placeholder Attribute

    HTML5 added a new placeholder attribute that has similar functionality to what you just created with JavaScript. Even if you use the HTML placeholder instead of JavaScript, you still learned some very useful concepts in this exercise.

Optional Bonus: Adding a Third Form Field

Use what you’ve learned to create a third form field to collect an email address:

  • You’ll need to add HTML (similar to the existing HTML for the first two form fields). Feel free to copy and paste!
  • You’ll need to add JavaScript (similar to the existing functions that work on the first two form fields).

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram