How to Read Form Element Info in Javascript
Chapter ix. Form Elements and Validation
9.0. Introduction
Outside of hypertext links,            course            elements were the very first form of interaction between web developers     and web page readers, and were also one of the commencement reasons for interest     in a scripting linguistic communication.
With the advent of JavaScript,            form            elements could be validated earlier the data     was sent to the server, saving the reader time and the website extra     processing. JavaScript tin can too be used to modify            class            elements based on the data the web reader     provides, such as filling a selection listing with the names of cities when a     certain state is selected.
The important point to remember when using JavaScript with            form            elements is that people turn JavaScript     off, so information technology tin't be a dependency for any form action. JavaScript enhances,     not replaces.
Annotation
Though validating the form on the client can save a round trip, every bit a sound design practice, you'll still want to validate the data on the server.
nine.1. Accessing Course Text Input Values
Problem
Yous need to access the contents of a text input              form              element using JavaScript.
Solution
Use the DOM to admission the              course              element:
var formValue = certificate.forms["formname"].elements["elementname"]. value;
Discussion
Forms in a web page can exist accessed through an object drove       (forms) via the              document              object. Each form has its       ain drove (elements) of              form              elements.
Accessing the              form              element's       value varies, based on the type of              form              element. For example, a text input or              textarea form              chemical element's value tin exist       accessed using the              value              attribute.       To admission the following              form              input       element's information:
<grade id="textsearch"> <input type="text" id="firstname" /> </form>
use the following JavaScript:
txtValue = document.forms["textsearch"].elements("design"].value;            Equally demonstrated before in the book, y'all tin can also access the input              class              element directly, via its       identifier:
var txtValue = document.getElementByid("pattern").value;            Withal, when you're working with a larger class, you lot're more probable going to want to piece of work with the DOM Level 0 class collections, in order to exist consistent.
You can also access the              form              element using an integer representing the form and the element's       position in the page. The kickoff              form              that appears in the folio is given an assortment index of zippo, the 2d an       index of one, and and so on. The same with the elements. And so to access the       example              form              element, use the       following:
var txtValue = document.forms[0].elements[one].value;
Using an array index is tricky, since it may be difficult to       make up one's mind the location of a specific class and chemical element. In addition,       adding a new form or element can make for incorrect JavaScript, or a web       folio awarding that doesn't perform every bit expected. However, information technology'south also a       elementary fashion to process all              form              elements in a loop:
while (var i = 0; i < certificate.forms[0].elements.length; i++) {    var val = certificate.forms[0].elements[i].value; }            Note
Whenever you lot're accessing information from a text or other field where         the user can input any value he wants, before sending to the         database or displaying in the folio, yous will want to strip or encode         any harmful SQL, markup, or script that may be embedded in the value.         Yous can use                encodeURI                and                encodeURIComponent                in JavaScript for         encoding.
nine.2. Dynamically Disabling and Enabling Course Elements
Trouble
Based on some action or outcome, you want to disable, or enable, i       or more              form              elements.
Solution
Use the              disabled              holding to enable or disable              form              element(south), accessing the element via the       forms/elements collections:
document.forms["formname"].elements["elementname"].disabled=true;
or via direct access to an chemical element with an identifier:
certificate.getElementById("elementname").disabled=truthful;          
Discussion
It's non unusual to disable some fields in a              form              until information is provided or a       specific result occurs. An example would be clicking a radio button       enabling or disabling other              class              elements, such equally input text fields.
See Also
See Recipe 9.four       for an example of clicking radio buttons and enabling or disabling       specific              class              elements. See Recipe nine.8 for some other approach to       providing access to              form              elements       based on activity (hiding or showing              form              elements).
nine.3. Getting Data from a Form Element Based on an Result
Problem
You need to access information from a              course              element after an consequence.
Solution
Depending on the              form              element,       you can capture any number of events, and based on the event, process       the              form              element information.
If y'all want to validate a              form              field after the data in the field has changed, you can assign a office       to the              onchange              issue handler function for the element:
document.getElementById("input1").onchange=textChanged;            In the related function, access the              form              element'due south value:
var value = this.value;
Y'all can also adhere a function to a              class              element based on whether it gets or loses       focus, using the              onfocus              and              onblur              event       handlers. The              onblur              event handler       can be handy if yous want to ensure a              class              field has data:
document.getElementById("input2").onblur=checkValue;            In the role that checks to ensure some value is provided,       you'll outset demand to trim whatsoever whitespace. Since the              String              trim              method is not supported in IE8, the       following code uses a variation of the regular expression              String.replace              method covered in Affiliate two:
var val = this.value; val = val.replace(/^\s\s*/, '').supercede(/\s\south*$/, '') if (val.length == 0) alert("need value!");            You can capture keyboard events for              form              elements, such as              onkeypress              for a checkbox, but a click event       is triggered for most              form              elements       whether the chemical element is clicked on by a mouse or the spacebar is clicked       when the chemical element has keyboard focus:
certificate.getElementById("check1").onclick=getCheck;            In the part, you tin can and so access the checkbox              checked              holding:
var checked = this.checked; if (checked) { ...}          
Word
There are several dissimilar events based on the blazon of              course              element. Each can be captured, and the       appropriate event handler assigned a function.
Table 9-1       contains a list of              form              elements and       the events most commonly captured for the element.
Tabular array nine-i. Grade elements and commonly occurring events
|                          Elements  |                                                Events  |                     
|                                                      |                                                                            |                     
|                                                      |                                                                            |                     
|                                                      |                                                                            |                     
|                                                      |                                                                            |                     
|                                                      |                                                                            |                     
|                                                      |                                                                            |                     
|                                                      |                                                                            |                     
The list of elements isn't exhaustive, nor is the list of events,       but this gives you an idea of the more than commonly occurring              class              element/event pairings.
In the              grade              event handler       office, you can access both the event and the element to get       data well-nigh both. How you do this depends on your browser, and       too how yous assign the events.
For instance, if you use the DOM Level 0 issue handling in which you assign the event handler function direct to the event handler belongings:
document.getElementById("button1").onclick=handleClick;            In all browsers, yous can access the element using the element       context              this. Yet, if you lot use DOM Level 2 and up event handling,       such equally the following function, which provides cross-browser event       handling:
function listenEvent(eventObj, upshot, eventHandler) {    if (eventObj.addEventListener) {       eventObj.addEventListener(event, eventHandler,false);    } else if (eventObj.attachEvent) {       event = "on" + issue;       eventObj.attachEvent(result, eventHandler);    } else {       eventObj["on" + event] = eventHandler;    } }            You tin access the element context with              this              for Firefox, Opera, Chrome, Safari, but       non for IE8. For IE8, you lot'll have to access the chemical element using the              result              object:
function handleClick(evt) {    // cantankerous browser issue access    evt = evt || window.evt;     // cross browser element access    var elem;    if (evt.srcElement)       elem = evt.srcElement;    else       elem = this;          
Meet Also
See Chapter 2 for using regular       expressions with              form              elements, and       Chapter 7 for more on result handling, including       with              form              elements.
9.4. Performing an Action When a Radio Button Is Clicked
Problem
You want to perform an action based on which radio push button is clicked.
Solution
Adhere an              onclick              consequence handler       to each of the radio buttons; in the outcome handler function, perform       whatsoever activeness y'all need:
window.onload=function() {   var radios = certificate.forms[0].elements["group1"];   for (var i = 0; i < radios.length; i++)     radios[i].onclick=radioClicked; }  function RadioClicked() {     if (this.value == "ane") {       certificate.forms[0].elements["line_text"].disabled=true;    } }          
Discussion
One relatively mutual use for JavaScript is to modify              form              elements based on actions taken elsewhere       in the form. For example, clicking a specific radio push may disable       some elements, but enable others. To do this, you need to assign an       upshot handler office to a              form              element's event handler, so find out information about the chemical element       that received the event.
In the solution, a gear up of radio buttons with the name of              group1              are accessed from the form, and the              onclick              event handler for each is       assigned to a function named              functionRadioClicked. In the function,       backdrop associated with the clicked radio button are attainable via              this, which is a proxy for the owner       of the result. Via              this, we can detect       out information about the event'south owner, including the blazon of element       receiving the event ("radio"), the              tagName              ("input"), and the              value              ("one").
With this information, we can decide which of the radio buttons was clicked, and perform whatever activeness we demand based on this information.
One action associated with radio buttons is to enable or       disable other              course              elements when i or some other of the radio buttons is clicked. Example ix-ane shows a more than       complete demonstration of this blazon of action. In the example, three       radio buttons are paired with three text input fields. All three text       input fields are disabled when the web page is loaded. Clicking any one       of the radio buttons enables one input field and disables the other       two.
Instance 9-1. Disabling/enabling input elements based on a clicked radio button
<!DOCTYPE html> <head> <title>Radio Click Selection</title>  <style> :enabled {     border: 4px solid #ff0000;     padding: 5px 5px 5px 15px; }  :disabled {     border: 2px solid #cccccc; }  </manner> <script>  window.onload=function() {    // first, disable all the input fields   document.forms[0].elements["intext"].disabled=true;   document.forms[0].elements["intext2"].disabled=true;   document.forms[0].elements["intext3"].disabled=true;    // next, adhere the click consequence handler to the radio buttons   var radios = certificate.forms[0].elements["group1"];   for (var i = [0]; i < radios.length; i++)     radios[i].onclick=radioClicked; } function radioClicked() {    // find out which radio button was clicked and   // disable/enable appropriate input elements   switch(this.value) {     case "one" :        certificate.forms[0].elements["intext"].disabled=false;        document.forms[0].elements["intext2"].disabled=true;        document.forms[0].elements["intext3"].disabled=true;        break;     instance "ii" :        certificate.forms[0].elements["intext2"].disabled=false;        document.forms[0].elements["intext"].disabled=true;        document.forms[0].elements["intext3"].disabled=truthful;        break;     example "three" :        certificate.forms[0].elements["intext3"].disabled=false;        certificate.forms[0].elements["intext"].disabled=true;        document.forms[0].elements["intext2"].disabled=true;        break;   }  }  </script> </head> <body> <grade id="picker"> Group 1: <input type="radio" proper noun="group1" value="1" /><br /> Group 2: <input type="radio" proper name="group1" value="2" /><br /> Grouping 3: <input type="radio" name="group1" value="iii" /><br /> <br /> <input blazon="text" id="intext" /> <input type="text" id="intext2"  /> <input blazon="text" id="intext3"  /> </class> </torso>              The nonassociated text input fields are disabled with each new clicked result, in order to clear previous activity. In addition, to add a lilliputian flair to the case, new CSS3 functionality to manner enabled and disabled attributes is used in the example, as shown in Figure 9-one. The CSS3 setting works with all of the book target browsers except IE8.
                  
                
Figure 9-1. Modifying a form chemical element based on a radio button click
See As well
Run into Recipe 9.2 for       more information almost attaching event handlers to              form              elements, and getting information from       the elements in an event handler function.
9.5. Checking for a Valid Phone Number
Problem
You want to validate form information that requires a certain format, such every bit a valid phone number.
Solution
Admission the form field value, and then employ a regular expression to validate the format. To validate a U.Due south.-based telephone number (surface area + prefix + digits):
// filter out anything merely numbers to // standardize input var phone = document.forms[0].elements["intext"].value; var re = /\D+/g; var cleanphone = phone.replace(re,"");  // check length if (cleanphone.length < x) alarm("bad phone");          
Discussion
To validate grade fields, you demand to strip out any extraneous material first, and then examination only what is necessary. Phone numbers can be provided using unlike formats:
-                   
(314) 555-1212
 -                   
314-555-1212
 -                   
314.555.1212
 -                   
3145551212
 
All you really need are the numbers; everything else is simply syntactic carbohydrate. To validate a phone number, strip out anything that isn't a number, and then check the length, as shown in the solution.
Once validated, you tin can then reformat into a standard format, though commonly if you lot're going to store a phone number in a database, you desire to store information technology in the smallest form possible (all numbers).
Another way to ensure that the data is correct is to provide three fields for the number, and only let the number of characters for each field (iii-3-four). But it's probably simpler for yous and for your users to apply simply i field.
See Also
There are any number of regular expression formulas that piece of work for diverse validation purposes. See more on regular expressions in Affiliate 2. Also note that many JavaScript frameworks and libraries provide uncomplicated-to-utilize validation routines, where all you have to practice is requite each input element a class proper noun or some other indicator in social club to trigger proper validation.
See Recipe 14.2 for integrating accessibility into your forms using ARIA.
9.half-dozen. Canceling a Form Submission
Trouble
Y'all want to cancel a class submission if you find the data entered into the form fields invalid.
Solution
If the class fields don't validate, abolish the grade submission result using the technique appropriate to the consequence handling technique you're using. Hither, we're borrowing from Chapter vii (where we covered events):
// listen to an event function listenEvent(eventObj, event, eventHandler) {    if (eventObj.addEventListener) {       eventObj.addEventListener(event, eventHandler,imitation);    } else if (eventObj.attachEvent) {       issue = "on" + event;       eventObj.attachEvent(event, eventHandler);    } else {       eventObj["on" + event] = eventHandler;    } }   // cancel event function  cancelEvent (event) {    if (event.preventDefault) {       event.preventDefault();    } else {       event.returnValue = false;    } }  window.onload=function() {    var form = document.forms["picker"];    listenEvent(form,"submit",validateFields); }  function validateFields(evt) {    evt = evt ? evt : window.issue;    ...     if (invalid) {       cancelEvent(evt);    } }          
Discussion
In the aforementioned part you apply to validate the course field(s), cancel       the event. In the issue office, the              cancelEvent              function       checks to see if the              preventDefault              method is supported. If it is, information technology's called. If not, the event'south              returnValue              is gear up to simulated (abolish       event).
See Also
See Chapter 7 for more than data on effect handling.
9.7. Preventing Duplicate Form Submissions
Problem
Potential harm could occur if a user submits the same form multiple times. You want to prevent duplicate form submissions.
Solution
I approach is to provide a bulletin that the form has been submitted, and so provide some means to prevent the web page reader from submitting the course once again. In its simplest variation, the following would work:
function validateSubmission(evt) { ... alert("Thank you, we're processing your lodge right now"); document.getElementById("submitbutton").disabled=true; // disable          
Discussion
Multiple concurrent form submissions are ane of the worst problems that can occur in a user interface. Nearly people would exist unhappy if, say, they establish they had purchased two of the same particular when they were only expecting to purchase ane.
At that place are several unlike approaches you lot can take to preclude duplicate form submissions, and how strict you desire to be depends on the seriousness of the double submission.
For example, comment forms don't usually restrict form submission. Duplicate submissions may upshot in a message that duplicate comments have posted, and the first has been rejected. Even if the duplicate comment is posted, information technology's a small nuisance, rather than a serious problem.
Even so, it'due south essential to foreclose duplicate class submission with whatsoever kind of storefront, and annihilation that could upshot in unexpected charges to your web customers.
If you do restrict duplicate form submissions, provide some form of feedback to the customer. In the solution, I took a uncomplicated approach, popping up a message providing feedback to the users that the course has been submitted, then disabling the submit push button and so they can't click it again.
It's an OK arroyo, but we can take the security a little further. Instead of a popular upwards, we tin can embed a bulletin directly into the page. Instead of simply disabling the submit button, nosotros can also use a flag to doubly ensure that a submission tin can't be initiated while an existing course submission is being processed. Example ix-2 demonstrates a safer fashion to prevent duplicate course submissions.
Example nine-2. Demonstrating prevention of duplicate form submissions
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <championship>Prevent Duplication Grade Submission</title>  <style> #refresh {    display: none;    width: 200px; height: 20px;    background-color: #ffff00; } </style> <script> //<![CDATA[  var inprocess=fake;  window.onload=role() {    certificate.forms["picker"].onsubmit=validateSubmit;    certificate.getElementById("refresh").onclick=startOver; }  part validateSubmit() {    // foreclose indistinguishable form submission   if (inprocess) return;   inprocess=truthful;   document.getElementById("submitbutton").disabled=truthful;    // for example just   document.getElementById("refresh").manner.display="block";   document.getElementById("bulletin").innerHTML= "<p>We're now processing your asking, which can accept a minute.</p>";    // validation stuff   render false; }  function startOver() {    inprocess=false;    document.getElementById("submitbutton").disabled=false;    document.getElementById("message").innerHTML="";    document.getElementById("refresh").mode.display="none"; } //--><!]]> </script> </head> <torso> <form id="picker" method="post" action=""> Group ane: <input type="radio" proper name="group1" value="i" /> Group two: <input blazon="radio" name="group1" value="two" /> Group iii: <input type="radio" proper noun="group1" value="three" /><br /> <br /> Input 1: <input type="text" id="intext" /> Input ii: <input type="text" id="intext2"  /> Input 3: <input type="text" id="intext3"  /><br /><br /> <input type="submit" id="submitbutton" value="Send class" /> </form> <div id="refresh"> <p>Click to reset case</p> </div> <div id="message"> </div> </body> </html>              If you load the instance into a browser and click the Send Form button, it will become disabled and two new elements will brandish: a processing message and a button to refresh the page. The latter is included only because this is an case, every bit a way to reset the example.
Normally, in a form, a mail-processing web page will display with a confirmation of the action and a message of thanks, or whatever is appropriate. If Ajax is used to make the update, the form can be reenabled one time the Ajax processing is complete.
Trouble
Y'all want to hide              form              elements       until some event.
Solution
Environment the              course              elements that       will be hidden with a              div              element:
<form id="picker" method="mail service" action=""> Detail 1: <input type="radio" proper name="group1" value="one" /> Particular ii: <input type="radio" name="group1" value="two" /> Item 3: <input type="radio" name="group1" value="three" /><br /> <br /> <div id="hidden_elements"> Input 1: <input blazon="text" id="intext" /> Input ii: <input blazon="text" id="intext2" /> Input three: <input type="text" id="intext3" /><br /><br /> </div> <input type="submit" id="submitbutton" value="Send grade" /> </form>
Alter the              div's display to              none              when the page loads:
window.onload=function() {    document.getElementById("hidden_elements").manner.display="none";    //  attach the click result handler to the radio buttons   var radios = document.forms[0].elements["group1"];   for (var i = [0]; i < radios.length; i++)     radios[i].onclick=radioClicked; }            When the event to display the              form              elements occurs, change the              div              element's brandish so that the              course              elements are displayed:
function radioClicked() {    if (this.value == "ii") {     document.getElementById("hidden_elements").style.display="block";    } else {     document.getElementById("hidden_elements").style.brandish="none";    } }          
Discussion
In the solution, the subconscious              form              elements are surrounded by a              div              element in order to make it easier to work       with them as a group. Nevertheless, you lot could also command the display for       elements individually.
The CSS              display              holding allows       yous to completely remove elements from the folio (display="none"), as shown in Figure 9-2. This makes it an       platonic CSS property to utilize; the              visibility              property       will only hide the elements, but information technology doesn't remove them from the       display. If you used              visibility,       you'd have a gap between the displayed elements and the course       push button.
                  
                
Figure ix-2. Page with form elements removed from display
In the solution, clicking the 2d radio button displays the       input fields, as shown in Figure 9-three. Find in the       code that if you click on the first or tertiary radio push button, the              display              for the hidden elements is prepare to              none, simply in case it is currently       displayed afterwards a previous 2nd radio push selection.
You always want to take into account the state of the folio whenever yous're processing an event that changes the makeup of a form. If certain elements are only displayed for given course values, then any activity in the form should either check the electric current state of the form or simply reissue either the hide or evidence functionality, because it doesn't hurt to reshow a shown element or rehide one already subconscious.
                  
                
Figure ix-three. Page with subconscious form elements displayed
9.9. Modifying a Selection List Based on Other Class Decisions
Problem
Y'all want to change the contents of a second pick list based on the option made in a kickoff selection list.
Solution
Y'all have 2 options when it comes to modifying the contents of i selection list, based on the choice in another selection listing.
The outset is to query a database and build the selection list based on the pick. This is demonstrated in Recipe 18.9, which covers Ajax.
The second arroyo is to maintain a static copy of the second selection list options:
var citystore = new Assortment(); citystore[0] = ['CA','San Francisco']; citystore[1] = ['CA','Los Angeles']; citystore[2] = ['CA','San Diego']; citystore[3] = ['MO','St. Louis']; citystore[4] = ['MO','Kansas Urban center']; citystore[5] = ['WA','Seattle']; citystore[6] = ['WA','Spokane']; citystore[7] = ['WA','Redmond']; //And use this copy to rebuild the selection list: role filterCities() {   var state = this.value;   var metropolis = document.getElementById('cities');   city.options.length=0;    for (var i = 0; i < citystore.length; i++) {     var st = citystore[i][0];     if (st == land) {       var opt = new Option(citystore[i][1]);       endeavor {         city.add(opt,null);       } take hold of(e) {         city.add(opt);       }     }   } }          
Give-and-take
Pick lists are often built from straight database queries. To       prevent the lists from being too large, they may exist built based on       choices in other              form              elements, from       an Ajax-enabled query, an assortment, or even a hidden selection listing.
As the solution demonstrates, regardless of arroyo, the simplest and quickest way to populate the selection list is to first ready the options assortment list to goose egg, which deletes everything from the list; then go through the bachelor choice data, and based on whatever criteria, create new options with the option data and suspend to the empty pick listing.
To encounter this type of functionality in activity, Example 9-3 shows an unabridged application       that incorporates the code in the solution. Clicking a state volition       populate the second selection list with cities for that state. A              effort...catch              block is used when adding       the new option to the selection listing, because IE8 does not support the       second parameter for the chemical element's position in the              add              method. If the offset              add              method fails, the second is used.
Example 9-iii. Populating a selection list
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Populating Selection Lists</championship> <script> //<![CDATA[  var citystore = new Array(); citystore[0] = ['CA','San Francisco']; citystore[1] = ['CA','Los Angeles']; citystore[2] = ['CA','San Diego']; citystore[3] = ['MO','St. Louis']; citystore[4] = ['MO','Kansas Urban center']; citystore[v] = ['WA','Seattle']; citystore[half-dozen] = ['WA','Spokane']; citystore[seven] = ['WA','Redmond'];  window.onload=part() {   certificate.getElementById("state").onchange=filterCities; }  part filterCities() {   var state = this.value;   var city = certificate.getElementById('cities');   city.options.length=0;    for (var i = 0; i < citystore.length; i++) {     var st = citystore[i][0];     if (st == land) {       var opt = new Choice(citystore[i][1]);       try {         city.add together(opt,null);       } take hold of(e) {         city.add(opt);       }     }   } }  //--><!]]> </script> </head> <body> <form id="picker" method="mail service" activity=""> <select id="land"> <option value="">--</option> <option value="MO">Missouri</choice> <option value="WA">Washington</option> <option value="CA">California</option> </select> <select id="cities"> </select> </form> </body> </html>              If scripting is disabled in an awarding like this 1, the best choice is to hide the city selection list past default and display a push button (again by default) that submits the form and populates the city selection on a second page.
Encounter Also
See Recipe xviii.ix       for a demonstration of using Ajax to populate a selection list. More on       the              endeavor...catch              error handling in       Recipe 10.4.
Source: https://www.oreilly.com/library/view/javascript-cookbook/9781449390211/ch09.html
0 Response to "How to Read Form Element Info in Javascript"
Postar um comentário