Event listener for TD content - javascript

I need to have a function triggered when anything changes on a table. I have an event listener and it works perfectly if anything changes in the table, except simple text in <td>. I need the event listener (or anything else) to capture changes in the following structure:
<td id="x">Text</td>
Please find below the full code that I use. I need the alert to be displayed when anything on the last row of the table changes (last - IDs "2,0" and "2,1"). The "Change Text" button changes the text in the s that I am interested of capturing the events of.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<table id="foobar">
<tr>
<td id="aaa" name="YYY">
<select name="001" id="0,0">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</td>
<td id="bbb" name="XXX"><input name="CCC" id="0,1" type="text"></td>
</tr>
<tr>
<td><input name="CCC2" id="1,0" type="text"></td>
<td><input name="CCC3" ud="1,1" type="text"></td>
</tr>
<tr>
<td id="2,0" name="abc">TEST 1</td>
<td><div id="2,1">TEST 2</div> </td>
</tr>
<br><br>
</table>
<input type='button' onclick='changeText()' value='Change Text'/>
<script>
function changeText(){
var x=Math.random(100);
document.getElementById('2,1').innerHTML = x;
}
document.getElementById('foobar').addEventListener('change',function(e)
{
e = e || window.event;
var target = e.target || e.srcElement;
var name = target.id || target.getAttribute('name');
alert('the ' + name + ' element changed!');
},false);
</script>
</body>
</html>

Related

JavaScript, append HTML and reference IDs in function

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>

1 dropdown menu with multiple and different outputs

So I've got a bit of a challange..
I'm trying to get 2 or 3 predefined outputs from a input value.
The code is below, but what I need to get working is that is I select ball_1, ball_2, ball_3 or ball_4 the VLAN and IP are diffrent.
ball_1 needs to output VLAN 12 and IP 32 but ball_2 needs to be VLAN 22 and IP 33 as for ball_3 and ball_4 the VLAN needs to remain empty..
function showData() {
var theSelect = demoForm.demoSelect;
var firstP = document.getElementById('firstP');
var secondP = document.getElementById('secondP');
var thirdP = document.getElementById('thirdP');
firstP.innerHTML = (theSelect.selectedIndex);
secondP.innerHTML = (theSelect[theSelect.selectedIndex].value) - (10);
thirdP.innerHTML = (theSelect[theSelect.selectedIndex].value);
}
<form name="demoForm">
<select name="demoSelect" onchange="showData()">
<option value="zilch">Select:</option>
<option value="32">ball_1</option>
<option value="33">ball_2</option>
<option value="84">ball_3</option>
<option value="85">ball_4</option>
</select>
</form>
<table class=table2>
<tr>
<td>bla</td>
<td>VLAN</td>
<td>IP</td>
</tr>
<tr>
<td>
<p id="firstP"> </p>
</td>
<td>
<p id="secondP"> </p>
</td>
<td>
<p id="thirdP"> </p>
</td>
</tr>
</table>
bla is unused for now so that is not that important.
I've also found this bit of code which seems to better meet my needs but I can't get a dropdown menu to run the input value so it outputs a more or less correct value
<form
oninput="x.value=parseInt(a.value)*parseInt(300);y.value=parseInt(a.value)*parseInt(400);">
<table style="text-align: left; width: 100px;" border="1"
cellpadding="2" cellspacing="2">
<tbody>
<tr>
<td><input name="a" value="" type="text"></td>
</tr>
<tr>
<td><output name="x" for="a b"></td>
</tr>
<tr>
<td><output name="y" for="a b"></td>
</tr>
</tbody>
</table>
</form>
I've got some basic knowledge about hmtl and java I think but I can't get it to work properly or is it impossible?
thanks in advance
kind regards
Wouter
ps. I don't use a database and have 0 knowledge on how to build and run one, also where the site runs it's almost impossible to run a SQL server.
You are not accessing drop down selected value correctly, Please look below working code.
Javascript function for accessing drop down selected value and setting IP and VLAN
function showData() {
var ddlDemo = document.getElementById("ddlDemoSelect");
var selectedValue = ddlDemo.options[ddlDemo.selectedIndex].value;
if (selectedValue == 32) {
document.getElementById('firstP').innerText = "bla";
document.getElementById('secondP').innerText = "12";
document.getElementById('thirdP').innerText = "32";
}
else if (selectedValue == 33) {
document.getElementById('firstP').innerText = "bla";
document.getElementById('secondP').innerText = "22";
document.getElementById('thirdP').innerText = "33";
}
else {
document.getElementById('firstP').innerText = "";
document.getElementById('secondP').innerText = "";
document.getElementById('thirdP').innerText = "";
}
}
Html. I have added Id for drop down to access it later on.
<form name="demoForm">
<select id="ddlDemoSelect" name="demoSelect" onchange="showData()">
<option value="zilch">Select:</option>
<option value="32">ball_1</option>
<option value="33">ball_2</option>
<option value="84">ball_3</option>
<option value="85">ball_4</option>
</select>
</form>
<table class=table2>
<tr>
<td>bla</td>
<td>VLAN</td>
<td>IP</td>
</tr>
<tr>
<td>
<p id="firstP"> </p>
</td>
<td>
<p id="secondP"> </p>
</td>
<td>
<p id="thirdP"> </p>
</td>
</tr>
</table>

dynamically loaded form controls & links not clickable

Content loaded through AJAX into a div isn't clickable until the user zooms the page. This seems to reset or remap some clickable zone definition somewhere.
In some other cases, the "clickable zone" gets just a bit off and you can notice it as the mouse cursor changes in the wrong area, not under my input fields/buttons/links.
This issue is seen under Chrome and Mozilla, I'm not working with IE but it also happens there.
From the symptoms above, what can be the causes?
This is the code I'm using to load the elements, (I doubt it's too relevant since the content is effectively being loaded):
function reqHandler(xhr, section) {
var x = xhr;
var s = section;
this.callback = function() {
if (x.readyState == 4) {
var ss = document.getElementById(s);
if (ss != null)
ss.innerHTML = x.responseText;
stripAndExecuteScript(x.responseText);
}
}
};
function loadInto(page,section, wait) {
if (wait==null) wait = true;
if (wait) makeWait(section);
xhr = createXMLHttpRequest();
handler = new reqHandler(xhr, section);
xhr.onreadystatechange = handler.callback;
xhr.open("GET", page, true);
xhr.send(null);
}
stripAndExecute is just to eval the loaded content's javascript, but it isn't used, the loaded content has simple link tags and a form, but anyway here's the code:
function stripAndExecuteScript(text) {
var scripts = '';
var cleaned = text.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){
scripts += arguments[1] + '\n';
return '';
});
if (window.execScript){
window.execScript(scripts);
} else {
eval(scripts);
}
return cleaned;
}
HTML of the generated div content:
<form id="users_form">
<table>
<colgroup><col width="65px">
</colgroup><tbody><tr>
<td colspan="2">Llene todos los campos</td>
</tr>
<tr>
<td align="right">Nombre</td>
<td><input class="text_field" name="name" value="" type="text"></td>
</tr>
<tr>
<td align="right">E-Mail</td>
<td><input class="text_field" name="email" value="" type="text"></td>
</tr>
<tr>
<td align="right">Usuario</td>
<td><input class="text_field" name="user" value="" type="text"></td>
</tr>
<tr>
<td align="right">ContraseƱa</td>
<td><input class="text_field" name="password" type="password"></td>
</tr>
<tr>
<td align="right">Repita contraseƱa</td>
<td><input class="text_field" name="password_confirm" type="password"></td>
</tr>
<tr class="type_display_block">
<td align="right">Tipo</td>
<td><select class="text_field" name="type" style="width:100%;">
<option value="0">Administrador</option>
<option value="1">Gerente</option>
<option value="2">Normal</option>
</select></td>
</tr><tr>
<td colspan="2"><a class="button" style="float: right;" href="javascript:void(0);" onclick="doDBinsert();"><img alt="Enviar" src="http://localhost/eclipse/mensajesInternos/img/check.png" height="25px" width="25px">Enviar
</a></td>
</tr>
</tbody></table>
</form>
The element which becomes not clickable is the "Enviar" button in the bottom.
NOTE: I'm not using jQuery.
NOTE2: If I put the "Enviar" link not in the next row but in the next column next to the select, like this:
<tr class="type_display_block">
<td align="right">Tipo</td>
<td><select class="text_field" name="type" style="width:100%;">
<option value="0">Administrador</option>
<option value="1">Gerente</option>
<option value="2">Normal</option>
</select></td>
<td colspan="2"><a class="button" style="float: right;" href="javascript:void(0);" onclick="doDBinsert();"><img alt="Enviar" src="http://localhost/eclipse/mensajesInternos/img/check.png" height="25px" width="25px">Enviar
</a></td>
</tr>
this is, in a TD instead of a TR, the element "Enviar" is clickable again. Actually I discovered the Select controls are responsible for the wrong offset in other sections as well. This is reproducible under windows and linux in Mozilla Firefoz and Chrome.
A bug of some kind?...

DOM elements/innetHTML add to table from dialog

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/

Adding rows dynamically with jQuery

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);
});

Categories

Resources