www.webdeveloper.com
Results 1 to 7 of 7

Thread: Need Help in adding values of Multiple Fields containing same name using javascript

  1. #1
    Join Date
    Jul 2012
    Posts
    3

    Question Need Help in adding values of Multiple Fields containing same name using javascript

    Hey guys I am new in Javascript as well as in this site. I have a small problem hope you guys can help me out

    I will give a small example of the problem

    HTML Code:
    <html><body>
    <form name="form">
    <input type="button" onclick="addInput()" name="add" value="Add more rows" />
    </form>
    <div id="row">
    <input name="qty" type='text' value=''" /> <br /> // This is the quantity field
    <input name="price" type='text' value=''" /> // this is price field
    <input name="total" type='text' value=''" /> // This field should multiply the values of qty and price
    </div>
    <div id="row">
    <input name="qty" type='text' value=''" /> <br /> // This is the quantity field
    <input name="price" type='text' value=''" /> // this is price field
    <input name="total" type='text' value=''" /> // This field should multiply the values of qty and price
    </div>
    <input name="grandTotal" type='text' value='' />
    </body>
    </html>
    Now in the above code there are two set of rows containing input fields
    I have used the same name in the input field cuz in future if a user clicks on a Add more row he can have as many as he wants so how do I apply addition in all the generated fields dynamically using javascript and display in in the an answer input. this is just an example I will have more fields in the same form but just to be on point I have written this example.

    Now what I want to know here is how to multiply the qty and price field and display the answer in the total field. And then add the total fields and display the answer in grandTotal field.

    Hope I didn't confuse and you guys and would provide me an easy solution.

  2. #2
    Join Date
    Jun 2004
    Location
    Portsmouth UK
    Posts
    2,644
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    <script type="text/javascript">
    /*<![CDATA[*/
    
    function addInput(frm){
     var frm=document.forms[0],div=frm.getElementsByTagName('DIV')[0].cloneNode(true);
     frm.insertBefore(div,frm.getElementsByTagName('A')[0]);
    }
    
    function Totals(){
     var frm=document.forms[0],flds=[frm['qty'],frm['price'],frm['total']],total=0;
     for (var z0=0;z0<flds[0].length;z0++){
      if (isFinite(flds[0][z0].value*1)&&isFinite(flds[1][z0].value*1)){
       flds[2][z0].value=flds[0][z0].value*flds[1][z0].value;
       total+=flds[2][z0].value*1;
      }
     }
     frm['grandTotal'].value=total;
    }
    /*]]>*/
    </script></head>
    
    <body>
    <html><body>
    <form name="form">
    <input type="button" onclick="addInput()" name="add" value="Add more rows" />
    <div id="row">
    <span>quantity</span><input name="qty" type='text' value='' />
    <span>price</span><input name="price" type='text' value='' />
    <span>total</span><input name="total" type='text' value='' />
    </div>
    <div id="row">
    <span>quantity</span><input name="qty" type='text' value='' />
    <span>price</span><input name="price" type='text' value='' />
    <span>total</span><input name="total" type='text' value='' />
    </div>
    <a></a>
    <input name="grandTotal" type='text' value='' />
    <input type="button" name="" value="Totals" onmouseup="Totals();" />
    </form>
    </body>
    </html>
    Vic

    God loves you and will never love you less.

    http://www.vicsjavascripts.org/Home.htm
    If my post has been useful please donate to http://www.operationsmile.org.uk/

  3. #3
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,755
    Here's another, more object oriented take that should be easy to change in the future to add the ability to create new rows:
    Code:
    <!DOCTYPE HTML>
    <html>
    <body>
    
    <form id="products_form">
    	<button type="button" data-action="addRows">Add more rows</button>
    	<table>
    		<thead>
    			<tr>
    				<th>Quantity</th>
    				<th>Price</th>
    				<th>Total</th>
    			</tr>
    		</thead>
    		<tbody>
    			<tr>
    				<td><input name="qty" type='text' value=''></td>
    				<td><input name="price" type='text' value=''></td>
    				<td><input name="total" type='text' value=''></td>
    			</tr>
    			<tr>
    				<td><input name="qty" type='text' value=''></td>
    				<td><input name="price" type='text' value=''></td>
    				<td><input name="total" type='text' value=''></td>
    			</tr>
    		</tbody>
    	</table>
    	<input name="grandTotal" type='text' value=''>
    </form>
    
    <script type="text/javascript">
    function ProductsForm(form) {
    	this.form = form;
    }
    ProductsForm.prototype = {
    	init: function() {
    		var that = this;
    		this.form = (typeof this.form === "string") ? document.getElementById(this.form) : this.form;
    		this.form.addEventListener("click", function(event) {
    			that.handleClick(event);
    		});
    	},
    	handleClick: function(event) {
    		var action = event.target.getAttribute("data-action")
    		if (action) {
    			this[action](event);
    		}
    	},
    	addRows: function(event) {
    		event.stopPropagation();
    		event.preventDefault();
    		this.calculateTotal();
    	},
    	calculateTotal: function() {
    		var table = this.form.getElementsByTagName("tbody")[0];
    		var i = 0, length, grandTotal = 0, total = 0, quantity;
    		var quantityField, priceField, totalField, inputs;
    		
    		for (i = 0, length = table.rows.length; i < length; i++) {
    			total = 0;
    			inputs = table.rows[i].getElementsByTagName("input");
    			quantityField = inputs[0];
    			priceField = inputs[1];
    			totalField = inputs[2];
    
    			if (!this.validateField(quantityField) || !this.validateField(priceField) || !this.validateField(totalField)) {
    				return;
    			}
    
    			quantity = Number(quantityField.value);
    			price = Number(priceField.value);
    			total = quantity * price;
    			totalField.value = total;
    			grandTotal += total;
    		}
    
    		this.form.elements.grandTotal.value = grandTotal;
    	},
    	validateField: function(field) {
    		if (isNaN(field.value)) {
    			alert("Please enter a valid number");
    			field.select();
    			field.focus();
    			return false;
    		}
    
    		return true;
    	}
    };
    
    var form = new ProductsForm(document.getElementById("products_form")).init();
    
    </script>
    
    </body>
    </html>

  4. #4
    Join Date
    Jul 2012
    Posts
    3
    thanx I appreciate the effort shown from both of you guys. As a beginner in this language it really feels easy to get ahead when there are guys like you to help

  5. #5
    Join Date
    Jul 2012
    Posts
    3
    hey vwphillips can you also provide a script to delete row in front of each row and last but not least one more field of discount. I hope you dont mind. I find your scripts are really easy for a beginner to learn.

  6. #6
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,755
    Correction, the init() method should be:
    Code:
    	init: function() {
    		var that = this;
    		this.form = (typeof this.form === "string") ? document.getElementById(this.form) : this.form;
    		this.form.addEventListener("click", function(event) {
    			that.handleClick(event);
    		});
    
    		return this;
    	},

  7. #7
    Join Date
    Apr 2013
    Posts
    1

    Multiple updates using Javascript

    Quote Originally Posted by vwphillips View Post
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    <script type="text/javascript">
    /*<![CDATA[*/
    
    function addInput(frm){
     var frm=document.forms[0],div=frm.getElementsByTagName('DIV')[0].cloneNode(true);
     frm.insertBefore(div,frm.getElementsByTagName('A')[0]);
    }
    
    function Totals(){
     var frm=document.forms[0],flds=[frm['qty'],frm['price'],frm['total']],total=0;
     for (var z0=0;z0<flds[0].length;z0++){
      if (isFinite(flds[0][z0].value*1)&&isFinite(flds[1][z0].value*1)){
       flds[2][z0].value=flds[0][z0].value*flds[1][z0].value;
       total+=flds[2][z0].value*1;
      }
     }
     frm['grandTotal'].value=total;
    }
    /*]]>*/
    </script></head>
    
    <body>
    <html><body>
    <form name="form">
    <input type='text' id='userInput' value='Enter Percentage Change' />
    <div id="row">
    
    <input type="text" name="Default_Price[]" value="9.000000" >
    
    </div>
    <div id="row">
    <input type="text" name="Default_Price[]" value="94.000000" >
    
    </div>
    <a></a>
    
    <input type="button" name="" value="Update" onmouseup="Totals();" />
    </form>
    </body>
    </html>
    I am a novice at best with Javascript and any help would be appreciated. I am having a hard time trying to figure out what I need to do here. I ran across this thread and I modified the html form to display what I am trying to do, however everything else is just a copy past from a solution provided by vwphillips. I am dynamically generating a form using php and I want to be able to adjust all prices in the form by entering a Percentage in the first field then applying the percent of change to all prices on the form positive or negative.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles