Solved

jQuery Clone clones all fields on table row add instead of just one

Posted on 2013-01-22
8
693 Views
Last Modified: 2013-01-22
I'm trying to make my script only clone ONE field in a table row instead of all of them.  Not sure how to adjust.

Thanks in advance.

<form id="createDistribution" name="createDistribution" method="POST" enctype="multipart/form-data" action="">
		<input type="hidden" name="vendoracct" value = "<?=$vendorid?>">
		<div id="container" class="shadow">
			<div id="row">
				<div id="left">
					<strong>Description:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right">
						<input type="text" class="fieldclasssm" name="linedescr[]" value = "<? if (!empty($_POST['custRef'])) { echo "value='".safeData($_POST['custRef'])."'"; }?>" size="113" />
					</div>
				</div>
			</div>
			<div id="row">
				<div id="left">
					<strong>Amount:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right" class="total">
						<input type="text" readonly="readonly" />
					</div>
				</div>
			</div>
			<div id="row">
				<div id="left">
					<strong>Distributions:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right">
						<table border="0" width="800px" cellspacing="0" cellpadding="0" id = "distributions">
							<thead>
								<tr>
									<th class="colheader" width="100px">Qty</th>
									<th class="colheader" width="300px">Nominal Code</th>
									<th class="colheader" width="300px">Depot</th>
									<th class="colheader" width="100px">Amount</th>
									<th class="colheader" width="100px"><span class="boldblacklinks"><a href="#" id="add">[Add +]</a></span></th>
								</tr>
							</thead>
							<tbody class="lineBdy">
								<tr id="line_1" class="spacer">
									<td><input type="text" class="qty fieldclasssm" name="distQty[]" size="5" value="" /></td>
									<td><input type="text" class="nominal fieldclasssm" name="distNomCode[]" size="35" value="" /></td>
									<td><input type="text" class="depot fieldclasssm" name="distDepot[]" size="35" value="" /></td>
									<td><input type="text" class="amount fieldclasssm" name="distAmount[]" size="10" value="" /></td>
									<td>&nbsp;</td>
								</tr>
							</tbody>
						</table>
						<input type="hidden" id="items" name="items" value="1" /> 
						<input type="hidden" id="numRows" value= "<?=$numRows?>" />
						<br /><br />
					</div>
				</div>
			</div>
			<div align="center"><br /><input type="submit" name="saveClose" class="btn" value = "Save & Finish Distribution"> <input type="submit" class="btn" name="saveCont" value="Save & Add New Item"><br /><br /></div>
		</div>
	</form>


<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () { 
    $("#usedefaultbill").click(function () {
        $("#newdivbill").hide();
     });
    $("#usealternatebill").click(function () {
        $("#newdivbill").show();
    });
	
    $("#usedefaultship").click(function () {
        $("#newdivship").hide();
     });
    $("#usealternateship").click(function () {
        $("#newdivship").show();
    });
	
$("#poType").change(function(){

$("#showcustref").hide();

 var chosenValue = $("#poType").val();
if (chosenValue == "5" || chosenValue == "3" ) 
  
  {
    $("#showcustref").show();

}
  
});
	
	$("#compname").autocomplete({
		source: "autocomplete.php",
		minLength: 3,
		select: function(event, ui) {
			event.preventDefault();
			$("#compid").val(ui.item.id);
			$("#compname").val(ui.item.label);
			$(':text[name=shipCompName]').val(ui.item.label);
			$(':text[name=shipAddress]').val(ui.item.address);
			$(':text[name=shipCity]').val(ui.item.town);
			$(':text[name=shipState]').val(ui.item.state);
			$(':text[name=shipZip]').val(ui.item.postcode);
		}
	});
		
$("#compid").change( function () {
  $("#submit").trigger('click');
}); 

	$("#add").click(function(){
		$("#line_1").clone(false).appendTo(".lineBdy");
		var newbk = ap.clone(true);
	});
	

$('.nominal').autocomplete({source:'suggestNominal.php', minLength:2});
$('.depot').autocomplete({source:'suggestDepot.php', minLength:2});
				
});
</script>

Open in new window

0
Comment
Question by:t3chguy
  • 4
  • 4
8 Comments
 
LVL 8

Expert Comment

by:soupBoy
ID: 38807417
In your selector, you can specify an exact occurrence by using .eq()

$('#TheTable td').eq(0) //returns the first occurrence
$('#TheTable td').eq(2) //returns the third occurrence
0
 
LVL 1

Author Comment

by:t3chguy
ID: 38807438
So that would be apart of my 'Add' function?

	$("#add").click(function(){
		$("#line_1").clone(true).appendTo(".lineBdy");
		$('#distributions td').eq(1) //returns the first nominal
	});

Open in new window


If that is correct, I'm still cloning all rows.
0
 
LVL 8

Expert Comment

by:soupBoy
ID: 38807505
If you are trying to clone just one 'td' in your table, then it should be the selector you are cloning...

      
$("#add").click(function(){
		$('#distributions td').eq(1).clone(true).appendTo(".lineBdy");
	});

Open in new window



Here is a fsFiddle showing an example...Clone a single td using .eq() and .clone()
0
 
LVL 1

Author Comment

by:t3chguy
ID: 38807531
Take a look at what is happening in the screenshot now...

The QTY box is covered by the new nominal code, and nominal creates a new td each time the add button is pressed, instead of creating a new row when it's pressed and carrying down the value.
1-22-2013-3-29-48-PM.png
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 8

Expert Comment

by:soupBoy
ID: 38807569
I believe I am a bit confused on what you are trying to do....

Are you wanting to add an entire new row when a button/link is clicked?

What are you trying to do?
0
 
LVL 1

Author Comment

by:t3chguy
ID: 38807582
Sure,

I have a table with an Add Row button, and one row showing by default.

A user can fill out an entire row, and click add, to add another row worth of data if they need.

The Nominal Code column is what I want to have cloned all the way throughout the nominal code column regardless of how many rows are added, because that typically will always be the same.

In the screenshot, the code is somehow cloning all fields each time the add row button is pressed, and I'm trying to get it so that only the Nominal Code is cloned down.
sh3.png
0
 
LVL 8

Accepted Solution

by:
soupBoy earned 500 total points
ID: 38807726
Take a look at this, it builds a new <tr> and populates it with the correct ID and class.

$('#add').on('click', function(){
   DistributionAddLine();
});


function DistributionAddLine(){
     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
    $(newRow)
    	.attr('id', 'line_' + (lastID + 1 ))
        .attr('class', 'spacer')
        .append(newTds)
    ;
    
    //empty out the fields, except the one you want to keep populated
    $(newRow).find('input').not(':eq(1)').val('');
    
    //add the new row to the table body
    $('tbody.lineBdy').append(newRow);
    
}

Open in new window


Here is a jsFiddle of your code and my function: Adding Row...
0
 
LVL 1

Author Closing Comment

by:t3chguy
ID: 38807769
Brilliant solution, thank you so much for your help and patience!  I've got one more open ticket if you're interested in taking a stab at it.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

DOM Attributes and Properties treatment with jQuery 1.6 by Ivo Stoykov jQuery (http://jquery.com/) 1.6 introduces .prop() (http://api.jquery.com/prop/) and .removeProp() (http://api.jquery.com/removeProp/) methods which allow modifying or removi…
Requirements JQuery 1.6+ HTML CSS Introduction This article was inspired by an EE question (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28372511.html) on how to make a page show some balloons animate up a page…
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…

910 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now