Solved

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

Posted on 2013-01-22
8
685 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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

by Julian Matz As of jQuery (http://jquery.com/) 1.4 the .live() method (http://api.jquery.com/live/) supports custom events as well as some standard JavaScript events that it previously didn't support. Among these is the submit event. Unlike …
Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)

760 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

18 Experts available now in Live!

Get 1:1 Help Now