Page 150 - CITS - Computer Software Application -TT
P. 150

COMPUTER SOFTWARE APPLICATION - CITS




           JavaScript allows you to access an element by index, id, or name. Suppose that you have the following signup
           form with two <input> elements:
           <form action=”signup.html” method=”post” id=”signup”>
               <h1>Sign Up</h1>
               <div class=”field”>
                       <label for=”name”>Name:</label>
                       <input type=”text” id=”name” name=”name” placeholder=”Enter your fullname” />
                       <small></small>

               </div>
               <div class=”field”>
                       <label for=”email”>Email:</label>
                       <input type=”text” id=”email” name=”email” placeholder=”Enter your email address” />
                       <small></small>
               </div>
               <button type=”submit”>Subscribe</button>

           </form>
           Code language: HTML, XML (xml)
           To access the elements of the form, you get the form element first:
           const form = document.getElementById(‘signup’);Code language: JavaScript (javascript)
           And use index, id, or name to access the element. The following accesses the first form element:
           form.elements[0]; // by index
           form.elements[‘name’]; // by name
           form.elements[‘name’]; // by id (name & id are the same in this case)Code language: JavaScript (javascript)

           The following accesses the second input element:
           form.elements[1]; // by index
           form.elements[‘email’]; //  by name
           form.elements[‘email’]; // by idCode language: JavaScript (javascript)
           After accessing a form field, you can use the value property to access its value, for example:
           const form = document.getElementById(‘signup’);

           const name = form.elements[‘name’];
           const email = form.elements[‘email’];
           // getting the element’s value
           let fullName = name.value;
           let emailAddress = email.value;Code language: JavaScript (javascript)
           Put it all together: signup form
           The following illustrates the HTML document that has a signup form. See the live demo here.
           <!DOCTYPE html>

           <html lang=”en”>
               <head>
                       <title>JavaScript Form Demo</title>




                                                           137

                             CITS : IT&ITES - Computer  Software Application - Lesson 37 - 46
   145   146   147   148   149   150   151   152   153   154   155