...

View Full Version : form update depending on which values were entered



nickyfraggle
12-07-2009, 02:28 PM
Hello,

I have a form that works out some basic math questions e.g. area etc.

I run a function when a form field is updated to do the calculations, however I'd like to run a different calculation depending on which form element was updated.

Is there a way to say something like:

if (area1 was updated) {
work out this calculation
}
if(area2 was updated) {
work out this calculation
}

and so on?

Thanks,

Nicola

gusblake
12-07-2009, 03:37 PM
var inputs=Array.prototype.slice.call(document.getElementsByTagName("input"));

for(i in inputs) {
inputs[i].addEventListener("keyup", getUpdate, false); //not sure about "keyup" here
}

function getUpdate() {
//'this' keyword=target element, so
alert(this.value)
//displays the value of whichever textbox was updated
}


then you could do something like



function getUpdate() {
switch(this.name) {
case "area1": //do something
case "area2": //etc
}
}

Philip M
12-07-2009, 06:02 PM
Why not simply:-


<input type = "text" name = "area1" onchange = "update(1)">
<input type = "text" name = "area2" onchange = "update(2)">

<script type = "text/javascript">
function update(area) {
if (area == 1) {
// do this calculation
}
if (area == 2) {
// do that calculation
}
}

</script>

Quizmaster: In mythology, what term for a potion that increases sexual desire is derived from the name of the Greek goddess of love?
Contestant: Viagra

nickyfraggle
12-08-2009, 11:00 AM
Thanks! That works really nicely! Looks so simple when you know how hey?!

Quick question - I got it working ok with a number to identify the field, but couldn't get it to respond to something like area1 - is there a way to do this (just out of curiosity)?

I think I was treating it as a string, which didn't work but neither did using it without ""!

Thanks again for your help.

Nicky

Philip M
12-08-2009, 11:30 AM
Is this what you mean?



<input type = "text" name = "area1" onchange = "update('area1')">
<input type = "text" name = "area2" onchange = "update('area2')">

<script type = "text/javascript">
function update(areaName) {
if (areaName == "area1") {
// do this calculation
}
if (areaName == "area2") {
// do that calculation
}
}

</script>

nickyfraggle
12-08-2009, 12:04 PM
Yes, but when I tried that it didn't work! Must have been doing something wrong!!

Thanks again for your help!

Nicola

Philip M
12-08-2009, 12:37 PM
Yes, but when I tried that it didn't work! Must have been doing something wrong!!

Thanks again for your help!

Nicola

onchange = "update('area1')" - perhaps wrong quotes?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum