Pete Harrison
Pete Harrison

Reputation: 95

Stuck with simple calculation from form elements

I'm using a script template to create chunks of code when a user clicks a button, this works fine, but I want to be able to calculate a total within these cloned regions so I have a in-line onBlur statement as follows

onblur = "multiply.call(this, this.form.elements.Qty{{ID}}.value, this.form.elements.Cost{{ID}}.value, this.form.elements.Total{{ID}})"

As the cloning function updates ID to a value this evaluates to

onblur = "multiply.call(this, this.form.elements.Qty1.value, this.form.elements.Cost1.value, this.form.elements.Total1)"

My function is

function multiply(one, two, three) {
    console.dir(three);
    document.getElementById(three).value = (parseFloat(one) + parseFloat(two)).toFixed(2); // error here
};

If I display one and two they have the values from the form, however I get an error writing back to the for of Uncaught TypeError: Cannot set property 'value' of null.

The console shows the ID of the element three as Total1

I think this might be something to do with the jQuery clone and the DOM not being updated. The values are passed OK, but the object might not be.

Any ideas?

Upvotes: 0

Views: 52

Answers (1)

Maen
Maen

Reputation: 10698

document.getElementById(three) returns no match (thus the undefined).

You're passing an element to your function multiply as parameter three, and you're later using it as a string representing the ID of it.

If three is verified to be an element, don't call document.getElementById(three).value in first place, but directly three.value.

Upvotes: 1

Related Questions