www.webdeveloper.com
Page 1 of 3 123 LastLast
Results 1 to 15 of 41

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

  1. #1
    Join Date
    Feb 2014
    Posts
    22

    Help with passing values thru HTML and .js file

    I was given a task to create a form, which I have done

    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="jsAssignTwo.js">
    function formInfo()
    {
    }
    </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="useremail@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="formInfo();"/></p>
    </form>
    
    
    </body>
    
    </html>
    I then made a .js file and did all the validation, which seemed to work perfectly fine. However I was told that each functions of mine needed to be independent from my HTML code and should be able to pass the value to the function in .js and get a return value (with no getElementById in the .js file).

    .js file
    Code:
    	// Global variables used for form
        var missing = false;													// Boolean error message check
        var error = "";															// Error message
    
    // Set focus on the first field 
    function setFocus(f)
    {
    	// Set focus on first name
    	var f = first.value.focus;
    }
    	
    function firstName(fN)
    {
    	// Validate the first name
    	if (document.billingForm.first.value == "")
    	{
    		missing = true;
    		error += "\nPlease provide your first name";
    		first.focus();
    		first.select();
        }
    }
    function cityValidate(cV)
    {
    	var cityLength = city.value.length;										// Checking length for city
    	
    	// 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";
    		city.focus();
    		city.select();
    	}
    }
    function postalCode(pC)
    {
    	var rePost = /^[A-Z][0-9][A-Z]\s[0-9][A-Z][0-9]$/;						// Postal code expression
    	
    	// Postal code validation and format
    	if (!rePost.test(document.billingForm.postal.value))
    	{
    		missing = true;
    		error += "\nPlease provide your postal code. Ex: N1E 1E9";
    		postal.focus();
    		postal.select();
    	}
    }
    function phoneNumber(pN)
    {
    	var rePhone = /^\(?(\d{3})\)?[\.\-\/\s]?(\d{3})[\.\-\/\s]?(\d{4})$/;  	// Phone number expression
    	
    	// 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();
    	}
    }
    function emailAddress(eA)
    {
    	//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";
    		email.focus();
    		email.select();
        }
    }
    function errorMessages(eM)
    {
    	// 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();
    }

  2. #2
    Join Date
    Feb 2014
    Posts
    22
    Maybe this is a little better

    Code:
    <head>
    <title>Billing Form</title>
    <script type="text/javascript" src="jsAssignTwo.js"></script>
    <script type="text/javascript">
    
    function validateForm()
    {
        var rePost = /^[A-Z][0-9][A-Z]\s[0-9][A-Z][0-9]$/;                  
        var rePhone = /^\(?(\d{3})\)?[\.\-\/\s]?(\d{3})[\.\-\/\s]?(\d{4})$/;  
        var error = "";
        var missing = false;
        var cityLength = city.value.length; 
        var first = document.billingForm.first.value;                   
        var city = document.billingForm.city.value;
        var postal = document.billingForm.postal.value;
        var phone = document.billingForm.phone.value;
        var email = document.billingForm.email.value;
        var sF = document.getElementById("first").focus();
    
        if (first == "")
        {
            missing = true;
            error += "\nPlease provide your first name";
        }
        if (city == "" ||  cityLength < 3) 
        {
            missing = true;
            error += "\nPlease provide your city must be greater then three characters";
        }
        // Postal code validation and format
        if (!rePost.test(postal))
        {
            missing = true;
            error += "\nPlease provide your postal code. Ex: N1E 1E9";
        }
        if (!rePhone.test(phone))
        {
            missing = true;
            error += "\nPlease provide your phone number Ex: 5192125598, 519 212 5598, or (519) 212 5598";
        }
    
        if (email.search(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/) == -1) 
        {
            missing = true;
            error += "\nInvalid email Ex: usersemail@domain.com";
        }
        // 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");
        }
    }
    // Set focus on the first field 
    
    </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>
    However I was asked to use .js library to try to validate these form. Something like this

    Code:
    function setFocus(firstFocus)
    {
        first.focus();
    }
    function validate(fN, cY, pL, pE, eM)
    {
    }
    
    // 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();
    }
    As you can see anyone can take the capitalization and trim and use it on there form through my .js library. However I'm having trouble on were to begin with coding the validation in the js library and getting it into my HTML. If anyone can help on were to begin and I hope this is clear if not just ask me what I wasn't clear on. Thanks

  3. #3
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    248
    Quote Originally Posted by JavaWinter View Post
    ...needed to be independent from my HTML code...
    In this context, is the formInfo function a problem? You can put all of JavaScript code into two or more separate files, define each function you need and then invoke it as needed. Putting your JS code into an external file and making a reference to that file through the src attribute makes each defined function a property of the Global object just as you have defined it inside of the <script> tags.

    Example:

    HTML Code:
    <!DOCTYPE html>
    <html>
    <head>
       <meta charset="UTF-8" />
       <title>Untitled</title>
       <script type="text/javascript" src="script.js"></script>
       <script type="text/javascript" src="script2.js"></script>
    </head>
    <body>
    </body>
    </html>
    script.js
    Code:
    function test() {return 'Hellooo world'};
    script2.js
    Code:
    function showMsg() {alert(test())}
    
    showMsg();
    Code to be executed inside a console:
    Code:
    'test' in this //prints true
    'showMsg' //prints true
    which proves that functions are properties of the global object.
    Last edited by tech_soul8; 02-10-2014 at 04:16 PM.

  4. #4
    Join Date
    Feb 2014
    Posts
    22
    Quote Originally Posted by tech_soul8 View Post
    In this context, is the formInfo function a problem? You can put all of JavaScript code into two or more separate files, define each function you need and then invoke it as needed. Putting your JS code into an external file and making a reference to that file through the src attribute makes each defined function a property of the Global object just as you have defined it inside of the <script> tags.
    No. I can't use getElementById, so I declare my variables there to pass it over to the .js file with that function, you can add things in there if you want, but the purpose here is to to put info in the .js file that isn't really connected to this HTML, but can be used for many other forms. If you look at this

    Code:
    function capitalize(capital)
    {
        capital.value = capital.value.charAt(0).toUpperCase() + capital.value.slice(1);
    }
    function trim(trimSpace)
    {
    	return trimSpace.trim();
    }
    This is in my .js file and isn't connect to my HTML, but it can be used there once I connect the src, but it can also be used in any other form without changes. This exactly where am I stuck on trying to get this to work for my validation in the same way. Hope this makes sense.

  5. #5
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    248
    You mean you're stuck up creating generic form validation function?

  6. #6
    Join Date
    Feb 2014
    Posts
    22
    Quote Originally Posted by tech_soul8 View Post
    You mean you're stuck up creating generic form validation function?
    Some what yes. Lets say I have 5 text boxes for a form, and if those 5 text boxes are blank I return a error message, but instead coding all of that in the HTML I'm creating the .js and in that I will put a function identifying the blank text boxes, that way I can use it for all blank boxes instead of coding each individual text box and that way this .js file can be used on any form I create as it will have the function I need.

  7. #7
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    248
    Ok... Then if you ask me the first thing that you should avoid is referencing your form by its name or by getElementById because each form in a different web document can have different name or id...

    So this for example:
    Code:
    if (document.billingForm.first.value == "")
    is not acceptable.

    You can obtain forms using the document.forms property or by traversing a dom tree and looking for a <form> tags. The same way you can obtain a collection of <input> elements by document.getElementsByTagName and then use the form property of the input element to check if it is referencing the same form and if true the next thing you can check for is its type through the use of the inputElement.type property. If it is a radio then you check for its value, if it is checked or not...
    Last edited by tech_soul8; 02-10-2014 at 05:10 PM.

  8. #8
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    248
    ...it all depends on things that you know or don't know. For example if you know that each different html document will have the same kind of a form, same elements, same order... then the only thing you have to be concerned of is how to get them without referencing them by their names.

    The greater problem would be if you don't know how many forms will a web document contain, the structure of a web document, where would they be located, how many elements will they contain... In this situation creating a generic valdiation function would be a bit of a problem and it would involve "a lot" of checking etc...
    Last edited by tech_soul8; 02-10-2014 at 05:20 PM.

  9. #9
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    248
    Another idea have just crossed my mind. You can create an input element inside each of your forms of type hidden and and name it as you wish (like a passphrase). Then you can search each form for that specific element and if founded you know you have your form and you can set some global variable to reference it inside any of your functions.

  10. #10
    Join Date
    Feb 2014
    Posts
    22
    I think I figured out a way, but I'm doing something wrong.

    .js file

    Code:
    var error = "";
    
    function first(first)
    {
        if(first == "")
        {
            error += "\nPlease enter your name";
        }
    	return first;
    }
    function validateAll()
    {
       	if (!error == "")
    	{
    		alert(error);
    		return false;
    	}
    }
    HTML
    Code:
    <p>First Name*:
    <input type="textbox" name="first" id="first" onBlur="this.value=trim(this.value); first(this.value)" onkeyup='capitalize(this)'></p>
    
    <p><input type="button" value="Proccess Payment" onClick="return validateAll();"/></p>
    this way I don't have to use script in the HTML or function and can use the .js file with other forms.

  11. #11
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    248
    I thought you need something different....

    Try this:

    Code:
    if (!(error == "")) //do something

  12. #12
    Join Date
    Feb 2014
    Posts
    22
    Yes, I apologize for that I myself had a hard time understanding what they needed done. I initially did have all this completed and working, but it wasn't how they wanted.

    Is that code for the validateAll()? If yes it still won't give me the alert.

  13. #13
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    248
    Yes, it was for validateAll func. It should work...

    This:

    Code:
    if (!error == '')

    is wrong because ! operator has higher precedence. than == and its operand is first converted to boolean prior comparison and '' converts to false. So that condition will never be true constructed like that.

    The above code in orior post should work...

  14. #14
    Join Date
    Feb 2014
    Posts
    22
    I've tried that you can check it here yourself...

    http://jsfiddle.net/WinterisComing/5jM6M/4/

  15. #15
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    248
    Oh, I just realized where is the problem. Alert is not showing up if the onblur event hasn't been fired?

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