Question

I have several radio buttons that get their value dynamically. Then I have some javascript that catches the values and adds them up so they display nicely in a text box.

(Basically like a calculator adding values for a total value)

Now, if someone selects another radio button, it still adds that value but the value of the last button in that group doesn't get subtracted. That's what I need to do is to subtract the deselected value.

My form values look like this: "5/55" Where 55 is the number I am using for my value. The text field I am updating is called "notify". So you see I am successfully adding the value in the notify field with the newly selected radio button value. Just how do I get rid of the old value when a new one is selected in a group?

Here is the javascript I am using:

<script>
function eventTrigger (e) {
    if (! e)
        e = event;
    return e.target || e.srcElement;
}

function radioClick (e) {
    var obj = eventTrigger (e);
    var notify = document.getElementById &&
                    document.getElementById ('notify');
    if (notify)
    var partsArray = obj.value.split('/');
        notify.value = Number(notify.value) + Number(partsArray[1]);
    return true;
}
</script>

Thank you for any help!

Was it helpful?

Solution

Keep it simple: recalculate your final result from scratch every time something changes. Messing around with subtracting the old value can get really complex really quickly and is not worth it, unless you have really complex calculations to perform that would benefit from the speedup. So, every time the user changes a selection, calculate your sum based on the currently selected values. Done.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top