appending class to rows added dynamically

Posted on 2013-07-01
Last Modified: 2013-07-15
I have a table that users can add rows dynamically to, and I want to append my 'amt' class to each row that is added.

This is important because it adds the dollar sign in front of all text when they begin to type.

It works on the first row, but cannot figure out how to get it appended on all rows that are added dynamically.

			<div id="row">
				<div id="left">
					<strong>Receipt Items:</strong>
				<div id="right">
					<i>Only add another line to the receipt below IF you have multiple items on one receipt.</i>
					<br /><br />
					<table border="0" width="825px" cellspacing="0" cellpadding="5" name="receipts" id = "receipts">
								<th class="colheader" width="125px">Receipt #</th>
								<th class="colheader" width="120px">Date</th>
								<th class="colheader" width="120px">Category</th>
								<th class="colheader" width="120px">Description</th>
								<th class="colheader" width="120px">Amount</th>
								<th class="colheader" width="145px"><span class="boldblacklinks"><a href="#" id="add">[Add +]</a></span></th>
							<tbody class="lineBdy">
								<tr id="line_1" class="spacer">
									<td><input type="text" class="receipt fieldclasssm" id="recLineReceipt[]" name="recLineReceipt[]" size="7" value = "<?=$receiptNumber?>"/></td>
									<td><input type="text" class="date fieldclasssm" id="recLineDate[]" name="recLineDate[]" size="10" value = "<?=date("m/d/Y", strtotime($today))?>"/></td>
									<td><select name="selectCategory[]" class="fieldclasssm">
												<option value = "">Select a Category...</option>
												<?php //Get Categories
												$getCats = mysql_query("SELECT id, nominalName FROM expense_nominalCodes ORDER BY id") or die("Get Cats: " . mysql_error());
												if(mysql_num_rows($getCats) > 0)
													while($catData = mysql_fetch_array($getCats))
														echo '<option value = "'.$catData['id'].'">'.$catData['nominalName'] . '</option>';
									<td><input type="text" class="lineDescr fieldclasssm" name="recLineDescr[]" id="recLineDescr[]" value = "<?=$_POST['recLineDescr']?>" size="40" /></td>
									<td colspan = "2"><input type="text" class="amt fieldclasssm" name="recLineAmount[]" id="recLineAmount[]" value = "<?=$_POST['recLineAmount']?>" size="12" /></td>
			<div align="center"><br /><br /><input type="submit" name = "saveAdd" class="btn" value = "Save & Add Another Receipt" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" name = "saveAdd" class="btn" value = "Save as Draft" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="btn"name="saveDraft" value = "Save & Finalize Expense Report" /><br /><br /></div>
<script type="text/javascript">

// Dollar Amounts
		$(function() {
			$('.amt').blur(function() {
				$(this).formatCurrency({ colorize: true, negativeFormat: '-%s%n', roundToDecimalPlace: 2, groupDigits: false });
			.keyup(function(e) {
				var e = window.event || e;
				var keyUnicode = e.charCode || e.keyCode;
				if (e !== undefined) {
					switch (keyUnicode) {
						case 16: break; // Shift
						case 17: break; // Ctrl
						case 18: break; // Alt
						case 27: this.value = ''; break; // Esc: clear entry
						case 35: break; // End
						case 36: break; // Home
						case 37: break; // cursor left
						case 38: break; // cursor up
						case 39: break; // cursor right
						case 40: break; // cursor down
						case 78: break; // N (Opera 9.63+ maps the "." from the number key section to the "N" key too!) (See: search for ". Del")
						case 110: break; // . number block (Opera 9.63+ maps the "." from the number block to the "N" key (78) !!!)
						case 190: break; // .
						default: $(this).formatCurrency({ colorize: true, negativeFormat: '-%s%n', roundToDecimalPlace: -1, eventOnDecimalsEntered: true });
	//Add new table row & clone date field
	$('#add').on('click', function(){
	   	$('.date').focus(function() {
	   	$('.receipt').focus(function() {

	$('#receipts td:contains("recLineAmount")').addClass('amt');
	function addReceiptItem(){
		 var lastID = $('tr[id*="line_"]').length,    
			 newTds = $('tr[id="line_' + lastID + '"] td').clone(),
			 newRow = document.createElement('tr');
		// add new id and class to row, append cloned tds
			.attr('id', 'line_' + (lastID + 1 ))
			.attr('class', 'spacer')
		//empty out the fields, except the one you want to keep populated
		// $(newRow).find('input').not(':eq(0)').val('');
		 // $(newRow).find('input').not(':eq(0)').val('');
		//add the new row to the table body
		$('.receipt').attr('readonly', true);
		$('.date').attr('readonly', true);


Open in new window

Question by:t3chguy
  • 2
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39290930
When you use the blur() function (or any shortcut to event binding) you only bind the event to elements that exist when the call is first made, so it doesn't automatically add the event to newly created elements. For this you need to delegate the event to something that does exist when the call is made. You do this using the on() function, so instead of:

$('.amt').blur(function() { ... });

Open in new window

you need something like:

$("#receipts").on("blur", ".amt", function() { ... });

Open in new window


Author Comment

ID: 39290978
When I changed that, and started typing in the form, everything disappeared...
LVL 43

Accepted Solution

Chris Stanyon earned 500 total points
ID: 39291020
OK...You're going to have to be a bit clearer that that - I can't see what your page looks like (before or after you've changed the code). Do you get any console errors, etc..

You may have to do the same with the keyup event, so you end up with something like:

$("#receipts").on("blur", ".amt", function() { ... });
$("#receipts").on("keyup", ".amt", function(e) { ... });

A link to a live page would be useful...otherwise I'm just guessing!

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question