SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Zealot keira's Avatar
    Join Date
    Aug 2005
    Location
    QLD - Australia
    Posts
    183
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Form Calculator - onchange event

    HI Guys, I'm wondering if anyone wouldn't mind lending me a hand with this little task I have as I have no experience in javascript really and it's a problem on a site I am expected to fix :S

    I have a form which requires that three empty fields be filled in by the user. I then want javascript to do two things:
    1) add them and show this value in another field.
    2)I also want to then add 2% to this value and show it in yet another field.
    (all prior to the form being submitted)

    The fields I want added together are these:

    HTML Code:
    <input name="txtPackageCost" 
    id="field1" type="text" 
    value="#NumberFormat(packageAdmin.Price, ",0")#" onChange="validateDollar(this);"> 
                 
    <input name="txtTaxes" 
    type="text" id="field2"  
    value="#NumberFormat(packageAdmin.Taxes, ",0")#" onChange="validateDollar(this); "> 
                  
    <input name="txtFuelSurcharge" 
    type="text" id="field3" 
    value="#NumberFormat(packageAdmin.FuelSurcharge, ",0")#" onChange="validateDollar(this); ">
    I was given this bit of help:

    give input fields an ID:
    HTML4Strict Code:

    <input type="text" id="field1" />
    <input type="text" id="field2" />
    <input type="text" id="field3" />
    Result: <span id="result"></span>

    Add events for "onchange" to the input elements to trigger a function which performs the formulas.
    JavaScript Code:

    function updateResult() {
    value = byId('field1') + byId('field2') //...
    value *= 1.02; // C/C surcharge
    byId('result').innerHTML = value;
    }


    Note the use of the cross browser compatible method of getting values of elements (for convenience):
    JavaScript Code:

    // get the element resource for a given ID
    function byId(id){
    return document.getElementById ? document.getElementById(id) : document.all[id];
    }
    But I don't know where to start to do what was suggested!
    I googled for ages but expect I need an expert to show me the light.

    As you can see my fields already do have a onchange event, does this matter?

    I posted this in the coldfusion forum because the app is in coldfusion but it shouldnt matter for this as its just the javascript i need help with.

  2. #2
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As you can see my fields already do have a onchange event, does this matter?
    Big time - do you want both functions to run? (yes), which order? (make sure the value entered is good and THEN calculate the sum/add 2&#37

    There are a few ways of doing this, here is one:
    Code:
    <html>
    <head>
    <script type="text/javascript">
    var dollarFields = ["field1", "field2", "field3"]; // ids of the fields we want to use validateDollar on
    var calcFields = ["field1", "field2"]; // ids of the fields that when change, recalculate the total
    
    // order of the event handler functions executing is important (validateDollar THEN calculateFields)
    
    window.onload = function () {
    	// first add the validateDollar function to the onchange events
    	for (var i=0; i < dollarFields.length; i++) {
    		var el = document.getElementById(dollarFields[i]);
    		addAListener(el, "change", validateDollar);
    	}
    
    	// now add calculateFields function
    	for (var i=0; i < calcFields.length; i++) {
    		var el = document.getElementById(calcFields[i]);
    		addAListener(el, "change", calculateFields);
    	}
    }
    
    function addAListener(el, ev, fn) {
    	// wrapper
    	if (el) {
    		if (el.addEventListener) {
    			el.addEventListener(ev, function () { fn(el); }, false);
    		} else if (el.attachEvent) {
    			el.attachEvent("on" + ev, function () { fn(el); });
    		}
    	}
    }
    
    // get the element resource for a given ID
    function byId(id){
    return document.getElementById ? document.getElementById(id) : document.all[id];
    }
    
    function calculateFields(el) {
    	var thevalue = parseFloat(byId('field1').value) + parseFloat(byId('field2').value); //...
    	thevalue *= 1.02; // C/C surcharge
    	byId('result').innerHTML = thevalue;	
    
    }
    function validateDollar(el) {
    	// insert validate function here
    	alert(el.id);
    
    }
    </script>
    </head>
    <body>
    <form>
    <input name="txtPackageCost" 
    id="field1" type="text" 
    value="75.00"> 
                 
    <input name="txtTaxes" 
    type="text" id="field2"  
    value="7.50"> 
                  
    <input name="txtFuelSurcharge" 
    type="text" id="field3" 
    value="6.00">
    </form>
    <span id="result"></span>
    </body>
    </html>

  3. #3
    SitePoint Zealot keira's Avatar
    Join Date
    Aug 2005
    Location
    QLD - Australia
    Posts
    183
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    okay I think I see, yes I would want them in the order you say. How do I put the extra onChange event? do I just seperate it by a semicolon? and would it be: "calculateFields(el);" ? I don't really understand how to call a function with ID's.. I know, I don't understand the basics so I'm over my head. But I'm hoping someone will baby me!

    & where does the result come up? do I put another field in between the span area to show the result? How is this done?

  4. #4
    SitePoint Wizard siteguru's Avatar
    Join Date
    Oct 2002
    Location
    Scotland
    Posts
    3,629
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    What Jim has shown should pretty much work as it is. (Nice method BTW Jim ) All that's missing is some code to actually validate the data entered into the dollar fields, and if all is OK then call the calculateFields function.

    The onchange events are already added, and the result shows within the <span id="result"></span> section ... i.e. immediately below the form.
    Ian Anderson
    www.siteguru.co.uk

  5. #5
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Right - you'll notice that the onload function sets the event handlers for onchange (it adds two handlers - first the validatedollar fn to the elements that require it, and then calculateFields).

    That should work as is - as siteguru said just add your validation code to the validateDollar function and give it a try.

  6. #6
    SitePoint Zealot keira's Avatar
    Join Date
    Aug 2005
    Location
    QLD - Australia
    Posts
    183
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Apologies Jim, I couldn't quite get my head around it but you are right it works as is.

    Thankyou so much, this was simple and so effective! Hopefully I can use it in the future. Cheers.


Bookmarks

Posting Permissions

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