www.webdeveloper.com
Page 2 of 3 FirstFirst 123 LastLast
Results 16 to 30 of 41

Thread: Help with passing values thru HTML and .js file

  1. #16
    Join Date
    Feb 2014
    Posts
    22
    Yes to a degree. Basically I'm going to do the same to most text field and put them in the onBlur event, but validateAll() should actually alert if those fields aren't filled in.

  2. #17
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    255
    Why not do something like this:

    Code:
    var error ='Please enter your name'
    then modify the if statements inside your first and validateAll functions to look like this:

    Code:
     
    // first function
    if (first) error = '';
    
    //validateAll function
    if (error) {
    alert(error);
    return false
    }

  3. #18
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    255
    It will also prevent multiple 'Please enter your name' errors of:

    Code:
    error += '\nPlease enter your name!
    statement in case that the user clicks more than once 'process payement' button without first filling his/hers name.

    Also note that use of a global variables is highly discouraged and should be best avoided. Some could very easly break your logic just by fireing up a console a change a value of your error variable.
    Last edited by tech_soul8; 02-11-2014 at 01:02 AM.

  4. #19
    Join Date
    Feb 2014
    Posts
    22
    The thing is I need to use the var error a few times. At the moment I'm just having trouble getting this code to work, but I'm going to have 5 text field and each text field will have an error message, which I want to pop up as a compound error message hence the var error ""; error += ""; then alert(error);

  5. #20
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    255
    Then why don't you pass the input object instead of a value to the first function. That way you can extract its id, value, class...whatever you want, call the validate function or something else, check for requirements and generate errors if any for that particular element. You do the same with each element that requires some checking etc..

    I'm at work right now and writing this from my smartphone so I cannot help you muc right now...

  6. #21
    Join Date
    Feb 2014
    Posts
    22
    I really do appreciate the help. When you have time can you show an example? I kind of see where your coming from, but I'm not sure where to exactly start with that. Thanks

  7. #22
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    255
    No problem. I'll try to show you some examples when I get home and try to help you out if no one provides you with any assistance in meanwhile...

  8. #23
    Join Date
    Feb 2014
    Posts
    22
    Thank you. I'll inform you here if I find out, but if you can I'd still like to see the examples for future reference

  9. #24
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    255
    Ok...Just to point me (or someone else) to the right direction. how do you plan to identify each input element and know which validation rules to apply? Can you use id,name...or for example the first function is going to check just for the names, not email addresses etc...

    For some other type of data (not names) let's say email addresses you're going to use different function...?

    Hope I make myself clear...

  10. #25
    Join Date
    Feb 2014
    Posts
    22
    Yes, so lets say this

    Code:
    function first(fName)
    {
    
        if (fName == "")
        {
             error+= "";
        }
    }
    function last(lName)
    {
         if (lName == "")
         {
             error += "";
         }
    }
    function email(eMail)
    {
         if (email...expression for the email)
        {
              error += "";
        }
    }
    .
    .
    .
    .
    function errorMessage()
    {
        if (!(error == ""))
       {
            alert(error);
       }
    }
    so like that, but I need to attach this to HTML forms. The point of this is, so say you and I decided to make 3 forms each this .js file we both could use for all those forms validating them etc, so its not tied to one form, hence why I'm avoiding using getElementById, document.etc. I should be able to transfer these function to any form without any problem. I hope this is clear

  11. #26
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    255
    Ok, it won't be a problem at all. Just for the record: Form elements will contain ids and names...but you'll obtain them with the different approach. So whoever is going to insert that elements into a web document-s make sure you state that id attribute is a requirement (doesn't matter you wont know its value in advance,though).

    Is that a problem? If no then great, if it is then different methods will be needed.

  12. #27
    Join Date
    Feb 2014
    Posts
    22
    It shouldn't be a problem, as long as it works and and the same method can be used in other forms to validate I don't see the problem.

  13. #28
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    255
    Ok! Then this would be my example:

    HTML Code:
    <!DOCTYPE html>
    <html>
    <head>
       <meta charset="UTF-8" />
       <title id='tit'>Untitled</title>
       <script type="text/javascript" src="valForm.js"></script>
    </head>
    <body>
       <form name='form1' method='get' onsubmit='return validateAll(this)'>
    	  <fieldset>
    		 <legend>Form1</legend>
    		 Name1: <input id='name1_f1' name='name1' type='text' /><br />
    		 Name2: <input id='name2_f1' name='name2' type='text' /><br />
    		 Name3: <input id='name3_f1' name='name3' type='text' /><br />
    		 Email: <input id='email_f1' name='email' type='text' /><br />
    		 Phone: <input id='phone_f1' name='phone' type='text' /><br />
    		 <input type='submit' name='submit' value='Process payments' />
    	  </fieldset>
       </form>
       <form name='form2' method='get' onsubmit='return validateAll(this)'>
    	  <fieldset>
    		 <legend>Form2</legend>
    		 Name1: <input id='name1_f2' name='name1' type='text' /><br />
    		 Name2: <input id='name2_f2' name='name2' type='text' /><br />
    		 Name3: <input id='name3_f2' name='name3' type='text' /><br />
    		 <input type='submit' name='submit' value='Process payments' />
    	  </fieldset>
       </form>
    </body>
    </html>
    Code:
    function validateAll(that) {
       var form = document[that.name], inpElems = form.getElementsByTagName('input');
       var nameElems = [], emailElems = []; phoneElems = [];
       var msg1 = "Enter your name!!!", msg2 = "Please enter a valid email address!!!";
       var msg3 = "Please enter a valid phone number!!!";
    		
       for (var i = 0; i < inpElems.length; i++) {
    	  var attValue = inpElems[i].getAttribute('name');
    				
    	  if (attValue.indexOf('name') >= 0) nameElems.push(inpElems[i]);
    		 else if (attValue.indexOf('email') >= 0) emailElems.push(inpElems[i]);
    		 else if (attValue.indexOf('phone') >= 0) phoneElems.push(inpElems[i]);
    	  }
          return processElems("name",nameElems,msg1) &&
             processElems("email",emailElems,msg2,/example@net.hr/) &&
             processElems("phone",phoneElems,msg3,/\d{9}/)
    		 	
       function processElems(t,e,msg,re) {
          var passed = true;
                
          for (var i = 0; i < e.length; i++) {
             var elem = document.getElementById(e[i].id);
                   
             switch (t) {
                case "name": {
                   if ((elem.value == msg) || (elem.value == "")) {
                      elem.value = msg;
                      passed = false;
                   }
                   break;
                }
                case "email":
                case "phone": {
                   if ((elem.value == msg) || !re.test(elem.value)) {
                      elem.value = msg;
                      passed = false;
                   }
                   break;
                }
                default: break;
             }
          }
          return passed;
       }
    }
    This example should work for any form of same kind as long as you stick to the naming rules (form name, ids, names of elements...). Hope it will suit you fine! If you have any questions just ask.

  14. #29
    Join Date
    Feb 2014
    Posts
    22
    That is really neat and its help, however isn't exactly what I was looking for I apologize.

    This is my first attempt

    HTML
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Billing Form</title>
    <script type="text/javascript" src="jsLib.js">
    </script>
    <!--CSS for formatting the form-->
    <style type="text/css">
        .container {
            width: 200px;
            clear: both;
        }
        .container input {
            width: 100%;
            clear: both;
        }
    
        </style>
    </head>
      
    <!--div for formatting purpose-->  
    <div class="container">
    <body onLoad="setFocus()" bgcolor="grey">
    <form action="http://cswin2k5/echo/default.asp" method="post" name="billingForm">
    <h2 id = "welcome">Billing Information</h2>
    Title: </div>
    <input type="radio" name="Titles" id="titleOne" value="Title" /> Mr.
    <input type="radio" name="Titles" id="titleTwo" value="Title" /> Mrs.
    <input type="radio" name="Titles" id="titleThree" value="Title" /> Miss.
    <input type="radio" name="Titles" id="titleFour" value="Title" /> Ms.
    <div class="container">
    <p>First Name*:
    <input type="textbox" name="first" id="first" onBlur="this.value=trim(this.value)" onkeyup='capitalize(this)'></p>
    <p>Last Name*:
    <input type="textbox" name="last" id="last" onBlur="this.value=trim(this.value)" onkeyup='capitalize(this)'></p>
    <p>Address:
    <input type="textbox" name="address" id="address" onBlur="this.value=trim(this.value)" onkeyup='capitalize(this)'></p>
    <p>City:
    <input type="textbox" name="city" id="city" onBlur="this.value=trim(this.value)" onkeyup='capitalize(this)'></p>
    <p>Province:
    <input type="textbox" name="province" id="province" onBlur="this.value=trim(this.value)" onkeyup='capitalize(this)'></p>
    <p>Postal Code*:
    <input type="textbox" name="postal" id="postal" onBlur="this.value=trim(this.value)" onChange="this.value=this.value.toUpperCase()"></p>
    <p>Country:
    <input type="textbox" name="country" id="country" onBlur="this.value=trim(this.value)" onkeyup='capitalize(this)'></p>
    <p>Phone:
    <input type="textbox" name="phone" id="phone" onBlur="this.value=trim(this.value)"></p>
    <p>Email:
    <input type="textbox" name="email" id="email" onBlur="this.value=trim(this.value)" placeholder="email@domain.com"></p>
    <p>Credit Card Holder*:
    <input type="textbox" name="holder" id="holder" onBlur="this.value=trim(this.value)" onkeyup='capitalize(this)'></p>
    <p>Credit Card*:</div>
    <input type="checkbox" name="visa" id="visa"> Visa
    <input type="checkbox" name="master" id="master"> MasterCard
    <input type="checkbox" name="american" id="american"> American Express</p>
    <div class="container">
    <p>Credit Card Number*:
    <input type="textbox" name="credit" id="credit" onBlur="this.value=trim(this.value)"></p>
    <p>Expiration Date*:
    </div>
    <select name="Exp month" id="expMonth">
    <option value="blank" selected></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
    <option value="11">11</option>
    <option value="12">12</option>
    </select>
    				
    <select name="Exp year" id="expYear">
    <option value="blank" selected></option>
    <option value="2014">2014</option>
    <option value="2015">2015</option>
    <option value="2016">2016</option>
    <option value="2017">2017</option>
    </select>
    
    <p><input type="button" value="Proccess Payment" onClick="validateForm();"/></p>
    </form>
    
    
    </body>
    
    </html>
    .js file
    Code:
    function setFocus()
    {
    	// Set focus on first name
    	document.getElementById("first").focus();
    }
    // Validation on form
    function validateForm()
    {
    	// Variables used for form
    	var rePost = /^[A-Z][0-9][A-Z]\s[0-9][A-Z][0-9]$/;						// Postal code expression
    	var rePhone = /^\(?(\d{3})\)?[\.\-\/\s]?(\d{3})[\.\-\/\s]?(\d{4})$/;  	// Phone number expression
        var missing = false;													// Boolean error message check
        var error = "";															// Error message
    	var dropdown = document.getElementById;									// Error check for drop box
        var cityLength = city.value.length;										// Checking length for city
    	var creditLength = credit.value.length;									// Checking length for credit card
        var rdoOne = document.getElementById('titleOne').checked;				// Radio error check for title
        var rdoTwo = document.getElementById('titleTwo').checked;				// ""
        var rdoThree = document.getElementById('titleThree').checked;			// ""
        var rdoFour = document.getElementById('titleFour').checked;				// ""
        var chkVisa = document.getElementById('visa').checked;					// Check error message for payment method
        var chkMaster = document.getElementById('master').checked;				// ""
        var chkAmerican = document.getElementById('american').checked;			// ""
        
    	// Error message for radio buttons
        if ((rdoOne=="")&&(rdoTwo=="")&&(rdoThree=="")&&(rdoFour==""))
        {
            missing = true;
    		error += "\nPlease select a title";
    		first.focus();
    		first.select();
        }
    	// Validate the first name
    	if (document.billingForm.first.value == "")
    	{
    		missing = true;
    		error += "\nPlease provide your first name";
        }
    	if (document.billingForm.last.value == "")
    	{
    		missing = true;
    		error += "\nPlease provide your last name";
    	}
    	if (document.billingForm.address.value == "")
    	{
    		missing = true;
    		error += "\nPlease provide your address";
    	}
    	// Error check for City and has to be longer then 3 characters
    	if (document.billingForm.city.value == "" ||  cityLength < 3) 
    	{
    		missing = true;
    		error += "\nPlease provide your city must be greater then three characters";
    	}
    	if (document.billingForm.province.value == "")
    	{
    		missing = true;
    		error += "\nPlease provide your province";
    	}
    	// Postal code validation and format
    	if (!rePost.test(document.billingForm.postal.value))
    	{
    		missing = true;
    		error += "\nPlease provide your postal code. Ex: N1E 1E9";
    	}
    	if (document.billingForm.country.value == "")
    	{
    		missing = true;
    		error += "\nPlease provide your country";
    	}
    	// Phone number validation and format
    	if (!rePhone.test(document.billingForm.phone.value))
    	{
    		missing = true;
    		error += "\nPlease provide your phone number Ex: 5192125598, 519 212 5598, or (519) 212 5598";
    		phone.focus();
    		phone.select();
    	}
    	//Email validation with expression
        if (email.value.search(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/) == -1) 
        {
            error += "\nInvalid email Ex: usersemail@domain.com";
        }
        if (document.billingForm.holder.value == "")
    	{
    		missing = true;
    		error += "\nPlease provide your credit card holders name exactly as it is written on the card";
    	}
    	// Error for check box
        if ((chkVisa=="")&&(chkMaster=="")&&(chkAmerican==""))
        {
            missing = true;
            error += "\nPlease select a credit card method";
        }
    	// Drop box validation
    	if (document.billingForm.expMonth.value == "blank")
    	{
    		missing = true;
    		error += "\nPlease select a expiry month from the drop down menu";
    	}
    	// drop box validation
    	if (document.billingForm.expYear.value == "blank")
    	{
    		missing = true;
    		error += "\nPlease select a expiry year from the drop down menu";
    	}
    	// Error for credit card, no blanks, must be numbers and greater then 8 digits
        if (document.billingForm.credit.value == "" || isNaN(credit) && creditLength < 8)
    	{
    		missing = true;
    		error += "\nPlease enter your credit card number Ex: 12345678";
        }
    	// Show all message in one alert box
        if (missing)
        {
    	// calling all messages
            alert("You have enter the following data incorrectly: \n " + error);
        }
        else
        {
    		// if form filled out correct inform customer
            document.write("Thank you for submitting your information");
        }
    }
    // Capital on every letter function
    function capitalize(capital)
    {
        capital.value = capital.value.charAt(0).toUpperCase() + capital.value.slice(1);
    }
    // Trim all white spaces
    function trim(trimSpace)
    {
    	return trimSpace.trim();
    }
    If you run you'll see that it should work fine most validation should work etc. However with all document stuff its unacceptable. They need this .js file as a library to hold the validation. If you look at my trim and capital its something like that. I could give you that code and it would most likely work on your code. The want the same with the text boxes that function should work with having any tie to the form, or being tied to a specific set of form hence the way I was doing it earlier. I do believe you could use a function or something in HTML and pass it to the .js if that is helpful (not too sure).

    Code:
    var first = document.billingForm.first.value
    Not sure if you can get first from HTML and pass it to the .js file, but it could be a possibility.

    To make it seem a bit more understandable in what they told me its like making a function that identifies a blank text box and being able to use that code for all the text box (instead of going first, last, address, etc validating for blanks), so somewhere in the text input section, onBlur, onChange, etc and validating the whole thing once clicked on submit. Alert with all the error is also a must.

  15. #30
    Join Date
    Feb 2014
    Posts
    22
    without having to tie it to any form, or specific forms*

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles