Skip to main content
Engineering LibreTexts

3.4: Processing Form Elements Using JQuery and Unobtrusive JavaScript

  • Page ID
    27548
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    This section will introduce the reader to how to implement and call functions for process an HTML form in JavaScript. It will use EBP and callbacks, and two JavaScript paradigms, unobtrusive JavaScript and Immediate Invoked Function Expressions (IIFE), currently considered best practice, will be introduced in this chapter.

    This section will use EBP to process the data on the HTML form implemented in the shown below. Each topic in this sub chapter will modify the head for the HTML file to show how to process the form element that is introduced in that section. The reader can copy the HTML form and simply replace the head as each new topic is covered to see how they work.

    One of the main uses of JavaScript is to provide the interactivity to a web page. This interactivity will be used to show how to process the data on a form and print it back to the user in an alert box. This will be presented in the following manner:

    1. A callback function will be added to the button so that when it is clicked the function will be called. The handling of the button will then be processed in the callback function.
      This section will introduce Unobtrusive JavaScript, and how to use the principals of Unobtrusive JavaScript to set a callback function.
    2. An illustration of how to handle each of the different form element types will be shown. These form elements are:

      2.1. A textbox

      2.2. A checkbox

      2.3. A radio button group

    The form presented here will be processed, and each of its elements printed out. In the subsequent sections, the entire head of the document will be shown in full as it is developed. To see how each option works, take the head from the subsection and insert it into this program. The final result will be a JavaScript program to process the data on the form and print it to the console.

    Program 60 - HTML form to be processed in Chapter 3.4
    
    <html>
        <head>
            <title>Map Example Input Screen</title>
            <script>
                // New code will go here
            </script>
        </head>
        
        <body>
            <h1>Map Example Input Screen</h1>
                

    <label for="title">Title</label> <input type="text" size="20"> </p>

    Map Options<br> <label for="resize">Allow map to be resized: </label> <input type="checkbox" /> <br/> <label for="recenter"> Allow map to be re-centered: </label> <input type="checkbox" checked /> </p>

    Type of Map<br> <input type="radio" name="maptype" value="XYZ Map"/> <label for="XYZMap">XYZ map </label> <br/> <input type="radio" name="maptype" value="StamemMap" checked /> <label for="StamenMap">Stamen Map </label> </p>

    Screen Size<br> <input type="radio" name="screenSize" checked value="600x480"/> <label for="XYZMap">600x480 </label> <br/> <input type="radio" name="screenSize" value="1024x768"/> <label for="XYZMap">1024x768 </label> <br/> <input type="radio" name="screenSize" value="1280x800"/> <label for="XYZMap">1280x800 </label> </p>

    Center of Map<br> <label for="lat">Latitude </label> <input type="number" /> <label for="long">Latitude </label> <input type="number" /> </p> <input type="button" value="Process Form" /> </body> </html>

    3.4.1 Including JQuery

    To use the JQuery library, it must be included. This is the first modification to the head of the program made. The head of the program is now:

    Program 61 – Inserting JQuery into the form
    
    <head>
        <title>Map Example Input Screen</title>
        <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.Java
    Script">
        </script>
        <script>
            // New code will go here...
        </script>
    </head>    
    

    3.4.2 Adding an Event Callback to a Button

    To begin processing the form, the Process Form button at the bottom of the form will be given functionality by setting the callback on the onClick event.

    In a button, the onClick event is raised when the button is pressed. This event behavior can be specified when the button is created, as in the following example that calls an alert when the button is pressed.

    <input type="button" value="Process Form"
        onClick="alert('Button is clicked')" />
    

    In this code, the JavaScript code to execute (e.g. creating an alert box) is assigned in a string to the onClick event. In the web page we are developing, putting all of the JavaScript code directly in the html button would be difficult and probably unreadable. The onClick can execute any JavaScript expression, so it is easy to call a function and put the extended behavior in the function and call that function when the button is pressed.

    <input type="button" value="Process Form"
        onClick="processForm()" /> 
    

    This method of providing a callback for a function is valid and works but represents an idiom that is out of favor. A style known as Unobtrusive JavaScript21 is currently considered best practice for developing web pages. One of the principals of Unobtrusive JavaScript is that HTML markup and JavaScript should not be mixed. This was done in the previous example, where a JavaScript statement was placed in the HTML input tag for the onClick event.

    To separate HTML markup from JavaScript, the JQuery $(document).ready function is used to associate the form element (the button) with a JavaScript function. To do this, first the button is given an id so that it can be retrieved from the DOM. This was already done in the HTML form above.

    <input type="button" value="Process Form"  />

    In the ready function, the DOM element for the button is retrieved, and an anonymous function is attached to its onClick event. This is illustrated in the following example.

    Program 62 - Head of HTML file to associate a button with a function
    
    <head> 
        <title>Map Example Input Screen</title>
        <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.Java   
    Script">
        </script>
        <script>
        // JQuery $(document.ready()) function
        $(function() {
            document.getElementById("processButton").onclick =
                (function(){
                    alert("button is pressed");
                });
            });
        </script>
    </head> 
    

    3.4.3 Processing a textbox

    In the previous example, an alert box was used to test if the program was wired correctly, e.g. that the processButton function was called when the button was pressed. It is important in any language to make sure parts of the program work before trying to build the entire program. Novice programmers will often attempt to write entire programs and end up with a 20-line program with 100 compiler errors, several logic errors, and no chance to make a working program. The first thing to do when writing a program is to break the program down into simple pieces and make each piece work while building those pieces into the larger program.

    This is true in languages like Java, C#, C/C++, etc., but is even more true in a language like JavaScript. In JavaScript, a single bad line of code can cause a program of 100’s of lines of working JavaScript to simply produce no output. These programs will often produce confusing errors, or no errors at all. In JavaScript, it is always best to build a program in stages, making sure each change has the desired effect.

    Now that the wiring for the button is working, the processing of the form can be implemented. For this program, processing means the element will write a message to the console.log. First, all of the text boxes will be processed. Note that the term textbox as used here includes input types other than text. Input types like number and calendar are also treated like text boxes.

    To process a textbox, its value attribute is retrieved. The value attribute contains the message in the textbox as a string. Note that JQuery is a little strange in that when it retrieves a form element, it retrieves it as an array, and so the first element in the array needs to be dereferenced to get the value. This is shown in the code below to get the value from the title textbox.

    Program 63 - Retrieving the text from a textbox using the JQuery array format.
    
    <script>
        $(function() {
            $("#processButton").click(function(){
                console.log("The title is " + $("#title")[0].value);
            });
        });
    </script>                        
    

    An alternative to using the array notation is to use the JQuery prop() (property) function, which was introduced in JQuery 1.6. Both of these work, but the prop() function is the emerging standard, and so will be used in this textbook. Processing all of the textboxes using prop function is shown below.

    Program 64 - Processing textboxes with JQuery
    
    <head>
        <title>Map Example Input Screen</title>    
        <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.Java
    Script">
        </script>
        <script>
            $(function() {    
                $("#processButton").click(function(){
                    alert("Be sure to check the console");
                    // Text Boxes
                    console.log("The title is " + $("#title").prop('value'));
                    console.log("The center of the map is latitude " +
                        $("#lat").prop('value') + " and longitude " +
                        $("#long").prop('value'));
                });                
            });
          </script>
    </head>    
    

    3.4.4 Processing a checkbox

    The next step to process the form is to process the checkboxes. Just like the textbox had a value property that contained the text that was entered, the checkbox has a checked property of that indicates whether or not it is checked. If the checkbox is checked, the property is true, else it is false. The checkbox also has a value property, but that is not used in this example.

    The processing of a checkbox is analogous to the processing of a textbox above. The checkbox object is retrieved from the DOM, and then the checked property, rather than the value property, is retrieved. This is shown in the code below:

    console.log("Allow the map to be resized? " +
        $("#resize").prop('checked'));
    console.log("Allow the map to be recentered? " +
        $("#recenter").prop('checked'));    
    

    The processing of the checkboxes is added to the head section of the file above, and the new HTML head is shown below.

    <head>
        <title>Map Example Input Screen</title>
        <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.Java
    Script">
        </script>
        <script>
            $(function() {
                $("#processButton").click(function(){
                    alert("Be sure to check the console");
                    
                    // Text Boxes
                    console.log("The title is " + $("#title").prop('value'));
                    console.log("The center of the map is latitude " +    
                        $("#lat").prop('value') + " and longitude " +
                        $("#long").prop('value'));
                    // Check Boxes
                    console.log("Allow the map to be resized? " +    
                        $("#resize").prop('checked'));
                    console.log("Allow the map to be recentered? " +
                        $("#recenter").prop('checked'));                    
                    });
                });
        </script>
    </head>                    
    

    3.4.5 Processing radio buttons

    Processing radio buttons is more complicated that textboxes and checkboxes. For check boxes, each box was processed separately, and these checkboxes only required retrieving a property (value or checked) from the object. Radio buttons are contained in a group, and so to get the value that is checked requires that the radio button group be processed to see which one radio button has been checked.

    To process radio buttons, the first step is retrieved all the buttons in the group by the name attribute, not id attribute. Unlike the id, which is unique, the name is not. And the name was used to group the radio buttons in the User Interface (UI). To process the radio button, all of the buttons having the same name are retrieved using the getElementsByName22 method as an array of individual radio buttons.

    The most straight forward way to process the radio buttons is to walk the array to see which array element is checked, and then retrieve the properties (id, value, etcetera) associated with that array element. This is shown below in the function below, where the document.getElementsByName function is used to get an array of radio buttons, and that array is then processed to find the checked item. If the item is checked (the checked attribute is true), the value attribute is printed.

    Note that for the radio button, the value attribute is used in this example. The value is set when the specific radio button was defined in the HTML in order to get a string associated with the radio button actually selected.

    Program 66 - For Loop to process radio buttons
    
    <head>
        <title>Map Example Input Screen</title>
        <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.Java
    Script">
        </script>
        <script>
            $(function() {
                $("#processButton").click(function(){
                    alert("Be sure to check the console");
                    
                    // Text Boxes
                    console.log("The title is " + $("#title").prop('value'));
                    console.log("The center of the map is latitude " +
                        $("#lat").prop('value') + " and longitude " +
                        $("#long").prop('value'));
                    // Check Boxes
                    console.log("Allow the map to be resized? " +
                        $("#resize").prop('checked'));
                    console.log("Allow the map to be recentered? " +
                        $("#recenter").prop('checked'));
                    // Radio Buttons
                    maptype = document.getElementsByName("maptype")
                    for (let i = 0; i < maptype.length; i++){
                        if (maptype[i].checked) {
                            console.log("The maptype is " + maptype[i].value);
                        }   
                    }
                    });
                });
        </script>
    </head>                                                                        
    

    JQuery has abstracted this loop into a single line that can be used to process the radio button.

    $('input:radio[name=maptype]:checked').prop('value'));

    This statement says that the elements that have the name maptype are an input radio button group, which JQuery is to loop through return the checked radio button. The value property of the selected radio button is then retrieved. The JQuery equivalent to the previous head code would be the following.

    <head>
        <title>Map Example Input Screen</title>
        <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.Java
    Script">
        </script>
        <script>
            $(function() {    
                $("#processButton").click(function(){
                    alert("Be sure to check the console");
                    
                    // Text Boxes
                    console.log("The title is " + $("#title").prop('value'));
                    console.log("The center of the map is latitude " +
                        $("#lat").prop('value') + " and longitude " +
                        $("#long").prop('value'));
                    // Check Boxes
                    console.log("Allow the map to be resized? " +    
                        $("#resize").prop('checked'));
                    console.log("Allow the map to be recentered? " +
                        $("#recenter").prop('checked'));
                        
                    // Radio Buttons                                            
                    console.log(
                        $('input:radio[name=maptype]:checked').prop('value'));
                    console.log(
                        $('input:radio[name=screenSize]:checked').prop('value'));
                    });
                });
        </script>
    </head>                                                        
    

    3.4.6 The final web page to process a form

    The following is the final result of the web page to create and process the form. If the reader has correctly implemented all the changes above, they should have this solution, but it is included here in case readers have issues.

    Program 67 - Final program to process a form
    
    <html>
    <head>
        <title>Map Example Input Screen</title>
        <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.Java
    Script">
        </script>
        <script>
            $(function() {
                $("#processButton").click(function(){
                    alert("Be sure to check the console");
                    
                    // Text Boxes
                    console.log("The title is " + $("#title").prop('value'));
                    console.log("The center of the map is latitude " +
                        $("#lat").prop('value') + " and longitude " +
                        $("#long").prop('value'));
    
                    // Check Boxes
                    console.log("Allow the map to be resized? " +
                        $("#resize").prop('checked'));
                    console.log("Allow the map to be recentered? " +
                        $("#recenter").prop('checked'));    
    
                    // Radio Buttons
                    console.log(
                        $('input:radio[name=maptype]:checked').prop('value'));
                    console.log(
                        $('input:radio[name=screenSize]:checked').prop('value'));
                    });
                });
        </script>
    </head>
    
        <body>
            <h1>Map Example Input Screen</h1>
                

    <label for="title">Title</label> <input type="text" size="20"> </p>

    Map Options<br> <label for="resize">Allow map to be resized: </label> <input type="checkbox" /> <br/> <label for="recenter"> Allow map to be recentered: </label> <input type="checkbox" checked /> </p>

    Type of Map<br> <input type="radio" name="maptype" value="XYZ Map"/> <label for="XYZMap">XYZ map </label> <br/> <input type="radio" name="maptype" value="StamemMap" checked /> <label for="StamenMap">Stamen Map </label> </p>

    Screen Size<br> <input type="radio" name="screenSize" checked value="600x480"/> <label for="XYZMap">600x480 </label> <br/> <input type="radio" name="screenSize" value="1024x768"/> <label for="XYZMap">1024x768 </label> <br/> <input type="radio" name="screenSize" value="1280x800"/> <label for="XYZMap">1280x800 </label> </p>

    Center of Map<br> <label for="lat">Latitude </label> <input type="number" /> <label for="long">Latitude </label> <input type="number" /> </p> <input type="button" value="Process Form" /> </body> </html>

    3.4.1 Quick Check

    1. What is a callback function? How is it used to process an event?
    2. Give two ways to associate a callback with a button? Which is preferred? Why?
    3. Are ids unique on a web page? Are names unique on a web page? How would you process each of these?
    4. Does callback code have to run a function?
    5. What is the difference between a Lambda and Anonymous function? Which (if either or both) are implemented in JavaScript?
    6. What is the Web Console? How do you access it? Why would you use it?
    7. What determines the radio buttons that make up a group?
    8. Retrieve and display using alert boxes, with and without JQuery, the input from a textbox, checkbox, and radiobutton,

    21 Unobtrusive JavaScript is a set of best practices, one of which not mixing HTML markup and JavaScript. For more information about Unobtrusive JavaScript, see: https://en.Wikipedia.org/wiki/Unobtrusive_JavaScript.

    22 Note that names of the methods. To retrieve a single object such as a checkbox or textbox, the method getElementById is called. Note that the string Element in this name is singular. To retrieve the radio button group, the getElementsByName is called. Not the string Elements is plural.


    This page titled 3.4: Processing Form Elements Using JQuery and Unobtrusive JavaScript is shared under a CC BY license and was authored, remixed, and/or curated by Charles W. Kann III.

    • Was this article helpful?