I have a form that shows a drop-down menu and a text field next to it:
<html>
<body>
<table>
<tbody class="project_wrapper">
<tr>
<td scope="row">
<select id="test_project" name="test_project[]">
<option selected>Select</option>
<option>10</option>
<option>20</option>
</select>
</td>
<td><input id="test_value" name="test_value[]" type="text" placeholder="Enter value"></td>
<td><div id="test_calc"></div></td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="3">
Add another project
</td>
</tr>
</tbody>
</table>
</body>
</html>
You can select one of the values in the drop-down, and when you enter a numeric value into the text field, on each keyup, it'll display the value multiplied by the selected value. You can also click the "Add another project" link and it'll append/create another drop-down and text field. This already works, and is done with the following Jquery code:
<script type="text/javascript">
$(document).ready(function(){
var addProject = $('.add_project');
var wrapper = $('.project_wrapper');
var projectHTML = `<tr>
<td scope="row">
<select id="test_project2" name="test_project[]" class="custom-select">
<option selected>Select</option>
<option>10</option>
<option>20</option>
</select>
</td>
<td><input id="test_value2" name="test_value[]" type="text" placeholder="Enter value"></td>
<td><div id="test_calc2"></div></td>
</tr>`;
$(addProject).click(function(){
$(wrapper).append(projectHTML);
});
});
$('#test_value').keyup(function(){
$('#test_calc').text(Math.round($(this).val() * $("#test_project option:selected").val()));
});
The problem is I can't get the multiplication function to work/display the result for any newly appended lines. Above you can see I tried hardcoding the values of test_value2 and test_calc2 and then added this below:
$('#test_value2').keyup(function(){
$('#test_calc2').text(Math.round($(this).val() * $("#test_project2 option:selected").val()));
});
I would expect the result (at least for one new appended line) to appear in the same way as for the first line, but nothing seems to happen. My goal is to get the results to appear for the appended line, and then also find a way to have that keyup calculation function work for any number of appended lines (rather than hardcode 2, 3, 4, etc. values).
The ids, I think, will need to be dynamically assigned as the lines are appended, and then the name will stay the same to hold the arrays for test_array and test_value which I'm going to receive and process via PHP.
Thanks!
Remove all your IDs from the template rows, use classes or name="" instead as your selectors
Assign an ID to your TBODY, we'll use it as the .on() event delegator
Use the "input" event, not the "keydown" event. You can also copy/paste values, remember?
on "input" - refer to the parent TR using .closest() before descending back (using .find()) to find the elements specific for that row
Use parseInt() or parseFloat() to handle input strings. Also remember to always fallback to a number i.e: 0 to prevent NaN results
jQuery(function($) {
const projectHTML = `<tr>
<td>
<select name="test_project[]" class="custom-select">
<option value="" selected>Select</option>
<option value="10">10</option>
<option value="20">20</option>
</select>
</td>
<td><input name="test_value[]" type="type" placeholder="Enter value"></td>
<td><div class="result"></div></td>
</tr>`;
const $projects = $("#projects"); // assign an ID to your tbody
const $addProject = $('.add_project');
const arrRow = () => $projects.append(projectHTML);
// Create new row on click
$addProject.on("click", arrRow);
// Add the first row
arrRow();
// use a delegator which is not dymanic (the TBODY in this case),
// and use delegated events to any ":input" element:
$projects.on("input", ":input", function(ev) {
const $tr = $(this).closest("tr");
const $project = $tr.find('[name="test_project[]"]');
const $value = $tr.find('[name="test_value[]"]');
const $result = $tr.find(".result");
const project = parseInt($project.val(), 10) || 0;
const value = parseFloat($value.val()) || 0;
const result = project * value;
$result.text(result);
});
});
<table>
<tbody id="projects"></tbody>
<tbody>
<tr>
<td colspan="3">
Add another project
</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
The IDs must be unique, instead whenever you add another row you duplicate the IDs.
Instead of IDs I changed them to class in order to combine this keyword with .closest() and .find() to get the values of interest.
Moreover, because you add new elements to the table you need to delegate the event.
If you change the select you need to calculate again, not only on typing into the input field.
var addProject = $('.add_project');
var wrapper = $('.project_wrapper');
var projectHTML = '<tr>\
<td scope="row">\
<select class="test_project" name="test_project[]" class="custom-select">\
<option selected>Select</option>\
<option>10</option>\
<option>20</option>\
</select>\
</td>\
<td><input class="test_value" name="test_value[]" type="number" placeholder="Enter value"></td>\
<td><div class="test_calc"></div></td>\
</tr>';
$(addProject).click(function () {
$(wrapper).append(projectHTML);
});
$(document).on('input', '.test_value', function (e) {
$(this).closest('tr').find('.test_calc').text(Math.round($(this).val() * $(this).closest('tr').find('.test_project option:selected').val() || 0));
});
$(document).on('change', '.test_project', function(e) {
$(this).closest('tr').find('.test_value').trigger('input');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody class="project_wrapper">
<tr>
<td scope="row">
<select class="test_project" name="test_project[]">
<option selected>Select</option>
<option>10</option>
<option>20</option>
</select>
</td>
<td><input class="test_value" name="test_value[]" type="number" placeholder="Enter value"></td>
<td>
<div class="test_calc"></div>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="3">
Add another project
</td>
</tr>
</tbody>
</table>
Related
I am using jQuery dynamic table inputs in my form.Whenever i select country,i get the value from select box.But when i increase dynamic button (+) and again select the country from select box from another input field.i get same value of country from first selectbox field
<table class="dynamic-fields-table">
<thead>
<tr>
<th >Country</th>
<th >City</th>
<th></th>
</tr>
</thead>
<tbody data-role="dynamic-fields">
<tr class="form-inline">
<td>
<select name="country[]" class="form-control">
<option value="1">USA</option>
<option value="2">Russia</option>
<option value="3">Japan</option>
</select>
</td>
<td>
<input type="text" name="city[]" class="form-control">
</td>
<td>
button data-role="add">Add</button>- // button for increasing or decreasing input
</td>
</tr>
</tbody>
</table>
In script file.When I select country at first it will come value right in console.but when i increase input form then i select again another country then value of country will give same as first time selected.So how should i give value of country i selected everytime i increase dynamically input button
$(document).on(
'click',
'[data-role="dynamic-fields"],
function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-inline:first- child').clone();
new_field_group.find('input').each(function(){
$(this).val('');
});
container.append(new_field_group);
updatecity()
}
);
$(document).on('change', " select[name='country[]']", function(){
updatecity();
});
function updatecity(){
$country = $(" select[name='country[]']").val();
console.log($country)
}
Currently, updatecity always gives you the value of the first result of $(" select[name='country[]']"). While the values of the other dropdown lists are ignored.
function updatecity(){
$country = $("select[name='country[]']").val();
console.log($country)
}
To make each dropdown list's call to updatecity behave with respect to its own value, you can add a parameter to updatecity to tell which country to update.
function updatecity($target){
$country = $target.val();
console.log($country);
}
Having the function signature changed, you will also need to update places where you call updatecity
$(document).on(
'click',
'[data-role="add"]',
function(e) {
// ...
updatecity($("select[name='country[]']"))
});
$(document).on('change', "select[name='country[]']", function(e){
updatecity($(this));
});
Also, the code you're showing will insert a new inline-form whenever <tbody> is clicked, so I changed the selector from [data-role="dynamic-fields"] to [data-role="add"]
As a sidenote, I notice that updatecity doesn't actually do anything except logging a value. You might want to have its behavior match its name.
Below I've attached a code snippet for demonstration.
$(document).on(
'click',
'[data-role="add"]',
function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-inline:first-child').clone();
new_field_group.find('input').each(function(){
$(this).val('');
});
container.append(new_field_group);
updatecity($("select[name='country[]']"))
}
);
$(document).on('change', "select[name='country[]']", function(e){
updatecity($(this));
});
function updatecity($target){
$country = $target.val();
console.log($country)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table class="dynamic-fields-table">
<thead>
<tr>
<th >Country</th>
<th >City</th>
<th></th>
</tr>
</thead>
<tbody data-role="dynamic-fields">
<tr class="form-inline">
<td>
<select name="country[]" class="form-control">
<option value="1">USA</option>
<option value="2">Russia</option>
<option value="3">Japan</option>
</select>
</td>
<td>
<input type="text" name="city[]" class="form-control">
</td>
<td>
<button data-role="add">Add</button><!-- button for increasing or decreasing input-->
</td>
</tr>
</tbody>
</table>
I am trying to get table tr and second td values using parents('tr) and closest('tr') javascript methods and after selected dropdown.But not working i have searched in google nut no use.If anyone know please help to find the solutions.
app.component.html:
<table>
<thead>
<tr>
<td>Emp id</td>
<td>Roll id</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<tr>
<td>12345</td>
<td>18956</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
<tr>
<td>12345</td>
<td>18906</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
<tr>
<td>12345</td>
<td>98956</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
<tr>
<td>12345</td>
<td>13956</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
</tbody>
</table>
app.component.ts:
getTdValue(e){
let target = e.target.closest('tr');
if (target && target.id) {
let td = target.find('td:nth-child(2)');
if (td) {
console.log("Second td value is ="+ td.value )
}
}
}
https://stackblitz.com/edit/angular-peioe6?file=src/app/app.component.html
First you need to have a second option element inside your select element in order to get any change events triggered.
<select (change)="getTdValue($event)">
<option></option>
<option>Get second td value of this row</option>
</select>
Then you can rewrite your getTdValue method as follows:
getTdValue(mouseEvent: MouseEvent) {
let target = <HTMLSelectElement> mouseEvent.target;
let td = <HTMLTableCellElement> target.closest('tr').childNodes.item(1);
console.log("This row ID is " + td.innerHTML);
}
See following StackBlitz
UPDATE
When target.closest doesn't work (Angular 6), it can be replaced by target.parentElement.parentElement as follows:
getTdValue(mouseEvent: MouseEvent) {
let target = <HTMLSelectElement> mouseEvent.target;
let td = <HTMLTableCellElement> target.parentElement.parentElement.childNodes.item(1);
console.log("This row ID is " + td.innerHTML);
}
You have an if statement that evaluates the following condition: target && target.id. Since none of your <tr> element have an ID, the statement will evaluate to false, and none of the logic contained therein will be executed.
Since you are not using the ID for anything, you can simply remove it:
getTdValue(e){
let target = e.target.closest('tr');
if (target) {
let td = target.find('td:nth-child(2)');
if (td) {
console.log("Second td value is ="+ td.value )
}
}
}
Okay. This is a long one. So I have a page with a table containing various information about cars and the dealerships they came from. There is a button to add more cars with different years. This button opens a dialog. The dialog has 3 drop downs and one text input. I need the information from each drop down and the text input to add to the parent page. I'm halfway there. The information is adding the value of the input box, the text to the parent table within the "son" part of the table. I need this also to add the chosen value of the "son" drop downs on the same row of this text. One more thing. The "father" drop down needs to direct where the "son" information goes. Currently, my text is adding a new row to the bottom of the table under no specific father. I have stripped my code as much as possible so it's not overwhelming to look at, if there's a bracket missing somewhere it's an oversight. Here is the code and html for the parent page.
<head>
<script>
function updateParent1(value1,value2) {
var table = document.getElementById("car_table");
var rowCount = table.rows.length;
//alert(rowCount);
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.innerHTML = "";
var cell2 = row.insertCell(1);
cell2.innerHTML = value2;
</script>
</head>
<body>
<legend>Vehicle Information</legend>
<input type="text" id="shore_count" />
<div class="add_icon"><img src="images/add-item-icon.png"/></div>
<table id="car_table">
<thead>
<tr>
<th>Dealership</th>
<th>Vehicle Details</th>
</tr>
</thead>
<tbody>
<tr class="row_blue_bold father" id="father3">
<td colspan="2" class="father_header">John Eagle Honda</td>
</tr>
<tr class="row_blue_bold son3">
<td> </td>
<td>Honda 2011 - Civic</td>
</tr>
<tr class="row_blue_bold son3">
<td> </td>
<td>Honda 2008 - Accord</td>
</tr>
<tr class="row_blue_bold father" id="father4">
<td colspan="2" class="father_header">John's Used Cars</td>
<td>
</tr>
<tr class="son4">
<td> </td>
<td>Toyota 2002 - Camry</td>
</tr>
</body>
and here is the iframe/dialog page.
<script type="text/javascript">
$(document).ready(function () {
var id =3;
for (i=0;i<parent.getDescCount();i++) {
id++;
var prot = $("#numbers").find(".prototype").clone();
prot.find(".id").attr("value", id);
prot.find(".apni").attr("value","");
$("#numbers").append(prot);
}
//End of Add button
$("img.exit").click(function () {
parent.$.nmTop().close();
});
$("img.save").click(function () {
var isError = false;
$("input").each(function(i) {
if(this.value == "") {
isError = true;
var newRow = "<tr style='background:#ffff99'><td colspan='4'>Please enter the year of this vehicle.</td></tr><tr>";
$(this).parent().parent().before(newRow);
}
});
if(isError) return;
for(var j=0;j<document.getElementsByName("select1").length;j++) {
parent.updateParent1(document.getElementsByName("select1").item(j).value,document.getElementsByName("text1").item(j).value);
}
parent.$.nmTop().close();
});
});
//Add button
$("img.add").click(function () {
var prot = $("#numbers").find(".prototype").clone().first();
prot.find(".apni").attr("value","");
$("#numbers").append(prot);
}
</script>
<body>
<div id="selMultipleTitle"> Add Vehicle Information </div>
<div id="btnExitDialog"><img src="images/exit.png" height="17" width="17" class="exit"/></div>
<table id="numbers">
<thead>
<tr>
<th><strong>Make</strong></th>
<th><strong>Dealership</strong></th>
<th><strong>Model</strong></th>
<th><strong>Year</strong></th>
</tr>
</thead>
<tr>
<tbody>
<td><select id="fatherDeal" name="select1">
<option selected>Select...</option>
<option>John Eagle Honda</option>
<option>Toyota of America</option>
<option>John's Used Cars</option>
</select></td>
<td><select id="sonMake">
<option selected>Select...</option>
<option>Honda</option>
<option>Toyota</option>
</select></td>
<td><select>
<option selected id="sonModel">Select...</option>
<option>Civic</option>
<option>Accord</option>
<option>Camry</option>
</select></td>
<td><input value="Enter year" id="sonComment" class="apni" name="text1"/></td>
<td> </td>
</tbody>
</tr>
<tr>
<td class="align_right"><img src="images/cancel.gif" height="21" width="21" class="exit"/> <img src="images/save-icon1.png" height="21" width="21" class="save"/></td>
</tr>
</table>
</body>
Thanks in advance.
You need a dropdown as a source
<select id="source">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
And a target table
<table id="target">
</table>
And of course some kind of controller, I used a button.
<button id="control">clickme</button>
Now you only have to bind an action to the button and make it append the contents you want from your source into your target.
$(function() {
$('#control').click(function() {
$("#target").append("<tr><td>"+$("#source").val()+"</td></tr>");
});
});
Here is a fiddle: http://jsfiddle.net/X5DUv/
What I require is a pretty standard feature. And I am sure its easy enough, but somehow I cant make it happen. Please help me out here.
This is the scenario-->
I have a struts form on a jsp, which takes in employee information. Now with every employee I want to associate some family members.
So for information of family members I want :
1.) A row of -- 1 select element and 3 text field elements -- in the end of the form.
2.) A 'add' button which appends such rows on demand for adding more family members.
I dont know how I can attach a screen shot to give you exact idea of what I want.
I have tried doing this, using javascript, but javascript adds standard HTML elements, because of which I am not able to access the value of those fields in my action class.(Please tell me if this is not the case, because then the only question that will remain is, why am I unable access those values)
Currently what I am trying:
JSP:
<s:form name="enterEmployeeInfo" id="enterEmployeeInfo" action="enterEmployeeInfo">
////OTHER FORM ELEMENTS//////////////
<table>
<tr>
<td>Relationship</td>
<td>Name</td>
<td>Age</td>
<td>Occupation</td>
</tr>
<tr>
<td>
<select name="rel">
<option value=""></option>
<option value="Father">Father</option>
<option value="Mother">Mother</option>
<option value="Spouse">Spouse</option>
<option value="Child">Child</option>
</select>
</td>
<td> <input name="rName[]"/></td>
<td> <input name="rAge"/> </td>
<td> <input name="rOccupation"/> </td>
<td colspan="4" align="right"><button type="button" onclick="tryFunc(this.parentNode);">Add</button></td>
</tr>
</table>
<s:submit value="Add Employee" name="submit"/>
<s:reset value="Reset" name="reset"/>
</s:form>
The JS:
function tryFunc(node){
var root = node.parentNode.parentNode;
var allRows = root.getElementsByTagName('tr');
var cRow = allRows[1].cloneNode(true);
var cInp = cRow.getElementsByTagName('input');
for(var i=0;i<cInp.length;i++){
cInp[i].setAttribute('name',cInp[0].getAttribute('name')+'_'+(allRows.length+1))
}
var cSel = cRow.getElementsByTagName('select')[0];
cSel.setAttribute('name',cSel.getAttribute('name')+'_'+(allRows.length+1));
root.appendChild(cRow);
}
With this I am able to add a new row of specified elements, but unable to access the field values in the action class. I would like to point out that I am not able to access even the first row's elements in action class (probably because they are standard HTML).
Any help is appreciated.
Thanks!!
here is the solution to the problem, for those still stuck on it.
In the jsp:
<s:form name="enterEmployeeInfo" id="enterEmployeeInfo" action="enterEmployeeInfo">
////OTHER FORM ELEMENTS//////////////
<table>
<tr>
<td align="center">Relationship</td>
<td align="center">Name</td>
<td align="center">Age</td>
<td align="center">Occupation</td>
</tr>
<tr>
<td>
<select name="rel">
<option value=""></option>
<option value="Father">Father</option>
<option value="Mother">Mother</option>
<option value="Spouse">Spouse</option>
<option value="Child">Child</option>
</select>
</td>
<td> <input name="rName"/></td>
<td> <input name="rAge"/> </td>
<td> <input name="rOccupation"/> </td>
</tr>
<tr>
<td colspan="4" align="right"><button type="button" onclick="tryFunc(this.parentNode);">Add</button></td>
</tr>
</table>
<s:submit value="Add Employee" name="submit"/>
<s:reset value="Reset" name="reset"/>
</s:form>
The JS:
function tryFunc(node){
var root = node.parentNode.parentNode;
var allRows = root.getElementsByTagName('tr');
var cRow = allRows[1].cloneNode(true);
root.appendChild(cRow);
}
Then in the action class, just define a variables like this:
private String rel[];
private String rName[];
private String rAge[];
private String rOccupation[];
Define their getters and setters, and you can access each element of each row in jsp like this :
rel[0], rel[1], ........
rName[0],rName[1], .......
etc......
As for copying the Value of select element to cloned row, its simple javascript. Just do this:
clonedSelect.selectedIndex = original.selectedIndex;
If you still have issues, comment. :)
I'm building a form where I need multiple optional inputs, what I have is basically this:
Every time a user presses the plus button a new row of form inputs should be added to the form, how can I do this in jQuery? Also, is it possible to automatically add a new row when all rows (or just the last row, if it's easier / faster) are filled? That way the user wouldn't need to press the plus button.
I'm sorry for asking maybe such a basic question but I'm still very green with jQuery, I could do this with PHP but I'm sure Javascript / jQuery plays a more appropriate role here.
#alex:
<!DOCTYPE html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript">
$form = $('#personas');
$rows = $form.find('.person');
$('a#add').click(function() {
$rows.find(':first').clone().insertAfter($rows.find(':last'));
$justInserted = $rows.find(':last');
$justInserted.hide();
$justInserted.find('input').val(''); // it may copy values from first one
$justInserted.slideDown(500);
});
</script>
</head>
<body>
<form id="personas" name="personas" method="post" action="">
<table width="300" border="1" cellspacing="0" cellpadding="2">
<tr>
<td>Name</td>
<td>More?</td>
</tr>
<tr class="person">
<td><input type="text" name="name[]" id="name[]" /></td>
<td>+</td>
</tr>
</table>
</form>
</body>
</html>
This will get you close, the add button has been removed out of the table so you might want to consider this...
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
return false;
});
});
</script>
HTML markup looks like this
<a id="add">+</a></td>
<table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td>Name</td>
</tr>
<tr class="person">
<td><input type="text" name="name" id="name" /></td>
</tr>
</tbody>
</table>
EDIT To empty a value of a textbox after insert..
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last #name').val('');
return false;
EDIT2 Couldn't help myself, to reset all dropdown lists in the inserted TR you can do this
$("#mytable tbody>tr:last").each(function() {this.reset();});
I will leave the rest to you!
As an addition to answers above: you probably might need to change ids in names/ids of input elements (pls note, you should not have digits in fields name):
<input name="someStuff.entry[2].fieldOne" id="someStuff_fdf_fieldOne_2" ..>
I have done this having some global variable by default set to 0:
var globalNewIndex = 0;
and in the add function after you've cloned and resetted the values in the new row:
var newIndex = globalNewIndex+1;
var changeIds = function(i, val) {
return val.replace(globalNewIndex,newIndex);
}
$('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds );
globalNewIndex++;
I have Tried something like this and its works fine;
this is the html part :
<table class="dd" width="100%" id="data">
<tr>
<td>Year</td>
<td>:</td>
<td><select name="year1" id="year1" >
<option value="2012">2012</option>
<option value="2011">2011</option>
</select></td>
<td>Month</td>
<td>:</td>
<td width="17%"><select name="month1" id="month1">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select></td>
<td width="7%">Week</td>
<td width="3%">:</td>
<td width="17%"><select name="week1" id="week1" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select></td>
<td width="8%"> </td>
<td colspan="2"> </td>
</tr>
<tr>
<td>Actual</td>
<td>:</td>
<td width="17%"><input name="actual1" id="actual1" type="text" /></td>
<td width="7%">Max</td>
<td width="3%">:</td>
<td><input name="max1" id="max1" type="text" /></td>
<td>Target</td>
<td>:</td>
<td><input name="target1" id="target1" type="text" /></td>
</tr>
this is Javascript part;
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year'+currentItem+'" id="year'+currentItem+'" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td>Month</td><td>:</td><td width="17%"><select name="month'+currentItem+'" id="month'+currentItem+'"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week'+currentItem+'" id="week'+currentItem+'" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"></td><td colspan="2"></td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual'+currentItem+'" id="actual'+currentItem+'" type="text" /></td><td width="7%">Max</td> <td width="3%">:</td><td><input name="max'+currentItem+'" id ="max'+currentItem+'"type="text" /></td><td>Target</td><td>:</td><td><input name="target'+currentItem+'" id="target'+currentItem+'" type="text" /></td></tr>';
$('#data').append(strToAdd);
});
});
//]]>
</script>
Finaly PHP submit part:
for( $i = 1; $i <= $count; $i++ )
{
$year = $_POST['year'.$i];
$month = $_POST['month'.$i];
$week = $_POST['week'.$i];
$actual = $_POST['actual'.$i];
$max = $_POST['max'.$i];
$target = $_POST['target'.$i];
$extreme = $_POST['extreme'.$i];
$que = "insert INTO table_name(id,year,month,week,actual,max,target) VALUES ('".$_POST['type']."','".$year."','".$month."','".$week."','".$actual."','".$max."','".$target."')";
mysql_query($que);
}
you can find more details via Dynamic table row inserter
Untested.
Modify to suit:
$form = $('#my-form');
$rows = $form.find('.person-input-row');
$('button#add-new').click(function() {
$rows.find(':first').clone().insertAfter($rows.find(':last'));
$justInserted = $rows.find(':last');
$justInserted.hide();
$justInserted.find('input').val(''); // it may copy values from first one
$justInserted.slideDown(500);
});
This is better than copying innerHTML because you will lose all attached events etc.
Building on the other answers, I simplified things a bit. By cloning the last element, we get the "add new" button for free (you have to change the ID to a class because of the cloning) and also reduce DOM operations. I had to use filter() instead of find() to get only the last element.
$('.js-addNew').on('click', function(e) {
e.preventDefault();
var $rows = $('.person'),
$last = $rows.filter(':last'),
$newRow = $last.clone().insertAfter($last);
$last.find($('.js-addNew')).remove(); // remove old button
$newRow.hide().find('input').val('');
$newRow.slideDown(500);
});