?
Solved

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

Posted on 2013-01-22
8
Medium Priority
?
806 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

 
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
 
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 2000 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

Understanding Linux Permissions

Linux for beginners: How to view the permissions associated with files and directories and also how you can change them.

Question has a verified solution.

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

Introduction HyperText Transfer Protocol (http://www.ietf.org/rfc/rfc2616.txt) or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to t…
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
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)
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…

765 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