Forums

Calculated elements based on other elements

sinemac 21 Mar, 2009
This isn't really a ChronoForms specific question, but since I'm using ChronoForms to do the forms I thought I'd ask it here first (and besides, there are probably some ChronoForms specific things I could do to accomplish what I'm after).

I want to create a form that includes some dynamic content, and I suspect that javascript/AJAX is the way to go - but I don't know how to do it.

There are four fields, two of which will be user determined, and the other two will be calculated based on what the user puts in the first two.

Field1 -> user input (dollar amount)
Field2 -> user input (dollar amount)
Field3 -> calculated -> (Field1 - Field2) with a max value of 500 - i.e., if(Field1 - Field2) > 500, then Field3 = 500, else Field3 = (Field1 - Field2)
Field4 -> calculated -> Field4 = Field1 - (Field2 + Field3)

So, what I'd like is for Field3 and Field4 to automatically adjust based on the calculated values whenever a value is changed in Field1 or Field2.

Any ideas on how to best accomplish this?

Thanks,
Scott
nml375 21 Mar, 2009
A rather simple javascript should be able to do this, I don't see the need for any Ajax extensions (unless you wish to hide the calculations from curios visitors).

Javascript isn't quite my primary language, but I'd probably create a function to do the maths, taking one argument (reference to the form object). This should allow us easy access to the Field1-4 fields.
Next, I'd add an onChange event to both Field1 and Field2, calling this function..

Code would be entered in the javascript box
function updatethis(form) {
  form.elements['Field3'].value = Math.min(500, form.elements['Field1'].value - form.elements['Field2'].value);
  form.elements['Field4'].value = form.elements['Field1'].value - form.elements['Field2'].value - form.elements['Field3'].value;
}

And your form would look something like this:

<input type="text" name="Field1" onChange="updatethis(this.form);"><br />
<input type="text" name="Field2" onChange="updatethis(this.form);"><br />
<input type="text" name="Field3"><br />
<input type="text" name="Field4"><br />
sinemac 21 Mar, 2009
Thanks, nml375 - just tested it, and your code works perfectly for what I need!!
This topic is locked and no more replies can be posted.

VPS & Email Hosting 20% discount

{item:title} {images:#}