Dankorw
Dankorw

Reputation: 47

JS - Function to multiply two form fields (with dynamic generated div)

I have 2 fields of a form (Price and Quantity), and I'd like to set on the resultant div ("answer") the product of those two. So far I've done something, but if I dinamically add a new row, with the same fields, of course I get a div with the same name of the old one. I'm trying to do some kind of a shopping cart.

HTML of the form

<input type='text' id='price' name='price' value='0'>
 <input type='text' id='qty' name='qty' value='0'     onblur="multiply.call(this,this.form.elements.price.value,this.form.elements.qty.value)">
<div id='answer'></div>

JS

function multiply(one, two) {
  if(one && two){
    var myTarget = document.getElementById("answer");
    myTarget.innerText = one*two;
  } else {
    this.style.color='red';
  }
}

and, of course, the JS for the generated HTML

document.getElementById('text').innerHTML += "...<input type='text' name='price'></td><td><input type='text' name='qty'></td><td><div id='answer'></div></td></tr></table>";}

Hope I made sense lol. Thanks!

Upvotes: 1

Views: 1673

Answers (2)

rupps
rupps

Reputation: 9887

Welcome to stackoverflow. As you might know, the ID of an HTML element must be unique. So you could dynamically generate your rows with the fields named "price_1", "quantity_1", .... "price_100".

Then create the multiply function and just call it with the row:

        function multiply(rowNumber) {

            var myTarget = document.getElementById("answer_"+rowNumber),
                myPrice=parseInt(document.getElementById("price_"+rowNumber)),
                myQuantity=parseInt(document.getElementById("qty_"+rowNumber));

            if (isNaN(myPrice) || isNaN(myQuantity)) {

                // put on red, or whatever. Also, you should check for negative values
                // so people don't trick the quantity field to get stuff for free :P

                myTarget.innerText="---";

            } else {

                 myTarget.innerText = myPrice * myQuantity;

            }
        }

There are a lot of other possibilities, just keep in mind the ID's must be unique !

BTW- A quick way to do parseInts with NaN protection that I use a lot can be:

 myQuantity =parseInt(document.getElementById("qty_"+rowNumber)) || 0;

because NaN's evaluate to false as a boolean. You might find this technique useful as well.

Upvotes: 0

Charles
Charles

Reputation: 323

Use class instead of id for elements that may be shown on the page multiple times. Otherwise if you are keeping track of the elements that are being added to the page you could give them an index like id="price_0", id="price_1", etc.

Upvotes: 1

Related Questions