Javascript modification needed - javascript

I need to be able to check a class value for a certain string. The class could have multiple values separated by commas. The code needs to be modified so when West is selected everything goes away except the rows that have West included in the class value. Examples:
<tr class="West"></tr> (shows up)
<tr class="West,NE"></tr> (shows up)
<tr class="NE"></tr> (doesn't show)
javascript
<script type="text/javascript">
$(document).ready(function(){
var links = $('#lb01'),
regions = $('.West,.NE,.Southeast,.East,.South,.Central,.Northeast,.HO,.National,.US,.Texas,.Mid-Central');
regions.not('.West').hide();
links.change(function(event) {
regions.hide().filter('.' + this.options[this.selectedIndex].id).show();
});
});
</script>
html
<div class="tabset">
<div id="tab1" class="tab-box">
<div class="form-holder">
<form action="#">
<fieldset>
<label for="lb01"><strong>Choose District:</strong></label>
<select id="lb01">
<option class="bound" id="West">WEST</option>
<option class="bound" id="NE">NE</option>
<option class="bound" id="Southeast">SOUTHEAST</option>
<option class="bound" id="East">EAST</option>
<option class="bound" id="South">SOUTH</option>
<option class="bound" id="Central">CENTRAL</option>
<option class="bound" id="Northeast">NORTHEAST</option>
<option class="bound" id="HO">HO</option>
<option class="bound" id="US">US</option>
<option class="bound" id="Mid-Central">Mid-Central</option>
<option class="bound" id="Texas">Texas</option>
</select>
</fieldset>
</form>
</div>
<div class="report-box">
<table>
<thead>
<tr>
<td class="name">Name</td>
<td class="department">Department</td>
<td class="title">Title</td>
<td class="district">District</td>
<td class="profile"> </td>
</tr>
</thead>
<tbody>
<tr class="West,NE,Southeast">
<td>Name1</td>
<td></td>
<td></td>
<td></td>
<td><a class="btn-profile" href="#">PROFILE</a></td>
</tr><tr class="West">
<td>Name2</td>
<td></td>
<td></td>
<td></td>
<td><a class="btn-profile" href="#">PROFILE</a></td>
</tr><tr class="East">
<td>Name3</td>
<td></td>
<td></td>
<td></td>
<td><a class="btn-profile" href="#">PROFILE</a></td>
</tr>

Firstly, you shouldn't have commas in your class attribute. Classes are space-delimited:
<tr class="West NE"></tr>
Now, all you need to do is this in your change function:
links.change(function(event) {
$('.report-box tr').hide().find('.' + this.value).show();
});

Ok, this is going to be a big post.
First of all, you can condense the regions variable by just selecting the elements, var regions = $('tr', '#regions'); - This is clean, a standard coders try and stick to, and more efficient/dynamic. Next, the easiest way for class comparison is by overloading the classes, so you would have class="West NE" instead of class="West,NE" - this allows you to use the jQuery.hasClass function which is extremely useful.
Based on what I just said, I came up with the new code:
$(document).ready(function(){
var links = $('#lb01');
var regions = $("tr","regions");
links.bind("change",function(){
regions.hide().hasClass(this.options[this.selectedIndex].id).show();
});
});

Do not use commas to separate your class names, for starters. That was probably the culprit if what you have isn't working.
Here's an alternate way of doing this:
$(document).ready(function() {
var $links = $('#lb01');
$(".report-box tbody tr").hide();
$('tr.West').show();
$links.change(function(event) {
var region = $(this).find(":selected").attr("id");
alert(region);
$(".report-box tbody tr").hide();
$(".report-box tbody tr." + region).show();
});
});
working example: http://jsfiddle.net/hunter/thz99/

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>

Maintain Form Value After Submission

I have an html (no php) form on a cloud-based server. I have no access to the server files. I am struggling to do two things:
1) Show/hide div based on dropdown value (I do have this working on my site, but for some reason it's not working in my jsfiddle)
2) Maintain the dropdown value after the form is saved.
//Use to hide Analysis div when analysisPub question is answered no
$('.analysisPub').on('change', function () {
if(this.value === "Yes"){
$("#analysis").show();
} else {
$("#analysis").hide();
}
});
/*Hide Analysis div by default*/
.analysis {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Does this publication include in any form?</td>
</tr>
<tr>
<td class="analysisPub" id="analysisPub" name="analysisPub">
<select class="analysisPub" id="analysisPub" name="analysisPub">
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
</tr>
</table>
<!-- ANALYSIS DIV -->
<div id="analysis" class="analysis">
<h1>
Analysis Details
</h1>
<table>
<tr>
<td><label>Project Name</label>
</td>
<td class="text-area">
</td>
</tr>
<tr>
<td><label>Manager Name</label>
</td>
<td class="text-area">
</td>
</tr>
</table>
</div>
I want the div to remain hidden if the user has chosen 'No' from the dropdown, and the div should remain visible if the user has chosen 'Yes'. Currently, it doesn't matter what the user chooses, whenever the form is saved and re-opened, the div defaults back to hidden (because of the CSS).
I am very new to javascript and this project has been dropped in my lap last minute (sigh).
You have 2 elements with the ID "analysisPub" in your markup, if you remove the ID from the td element and change
$('.analysisPub').on('change', function () {
to
$('#analysisPub').on('change', function () {
So that you are using the ID, your code works just fine.
To remember the choice you can use the localStorage API.
//Use to hide Analysis div when analysisPub question is answered no
$('#analysisPub').on('change', function() {
window.localStorage.setItem("showAnalysis", this.value);
if (this.value === "Yes") {
$("#analysis").show();
} else {
$("#analysis").hide();
}
});
// check if value is already remembered and set it to the saved value:
if (window.localStorage.getItem("showAnalysis")) {
$('#analysisPub').val(window.localStorage.getItem("showAnalysis"));
}
/*Hide Analysis div by default*/
.analysis {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Does this publication include in any form?</td>
</tr>
<tr>
<td class="analysisPub" name="analysisPub">
<select class="analysisPub" id="analysisPub" name="analysisPub">
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
</tr>
</table>
<!-- ANALYSIS DIV -->
<div id="analysis" class="analysis">
<h1>
Analysis Details
</h1>
<table>
<tr>
<td><label>Project Name</label>
</td>
<td class="text-area">
</td>
</tr>
<tr>
<td><label>Manager Name</label>
</td>
<td class="text-area">
</td>
</tr>
</table>
</div>

showing selections from drop downs in a table

i have set of drop downs with a select button below.
what i want to try to do is once the user has been through the three drop downs and pressed select, the option that is chosen is shown in a corresponding table in its assigned category
HTML:
<form method="POST">
<select name='first' id='first'>
<option selected="selected" value="nothing">choose</option>
<option value='opt_a'>opt a</option>
<option value='opt_b'>opt b</option>
</select>
<select name='sec' id='sec'>
</select>
<select name='third' id='third'>
</select>
<br />
<br />
<button id="select_btn" type="select" name="select">select</button>
<br />
<br />
<div id="result">
<table>
<tr>
<th>category</td>
<th>choice</td>
</tr>
<tr>
<td>choice 1</td>
<td></td>
</tr>
<tr>
<td>choice 2</td>
<td></td>
</tr>
<tr>
<td>choice 3</td>
<td></td>
</tr>
<tr>
<td>choice 4</td>
<td></td>
</tr>
<tr>
<td>choice 5</td>
<td></td>
</tr>
<tr>
<td>choice 6</td>
<td></td>
</tr>
<tr>
<td>choice 7</td>
<td></td>
</tr>
<tr>
<td>choice 8</td>
<td></td>
</tr>
</table>
</div>
</form>
JS:
data = {
opt_a: ['choose_1','choose_2','choose_3','choose_4'],
opt_b: ['choose_5','choose_6','choose_7','choose_8'],
choose_1: ['yes','no','unsure','still unsure'],
choose_2: ['yes','no','unsure','still unsure'],
choose_3: ['yes','no','unsure','still unsure'],
choose_4: ['yes','no','unsure','still unsure'],
choose_5: ['a','b','avg','unclear'],
choose_6: ['a','b','avg','unclear'],
choose_7: ['a','b','avg','unclear'],
choose_8: ['a','b','avg','unclear']
}
$('#first').change(function(){
var firstopts = ''
$.each(data[$(this).val()],function(i,v){
firstopts += "<option value='"+v+"'>"+v+"</option>"
})
$('#sec').html(firstopts)
})
$('#sec').change(function(){
var secopts = ''
$.each(data[$(this).val()],function(i,v){
secopts += "<option value='"+v+"'>"+v+"</option>"
})
$('#third').html(secopts)
})
CSS:
select{width:150px;}
#result{width:450px; border:2px solid #234323;}
td{width:225px; text-align:center}
th{background:#656454; color:#eee; text-align:center}
Thank You in advance for any help.
Since your data keys are called choose_N and your columns have the text choice N, you can match them by splitting the value and getting the last part:
var number1 = 'choose_1'.split('_')[1];
var number2 = 'choice 1'.split(' ')[1];
return number1 == number2; // corresponding choice
You could also annotate your HTML with the corresponding value, if you want something more exact:
<tr data-choice="choose_1">
<td>choice 1</td>
<td></td>
</tr>
$(myselector).data("choice"); // Will return "choose_1"
Now all you have to do is to select the right row (the one that corresponds to the value currently selected in #sec) and set the second column to the value currently selected in #third. You could do it on the click callback of the select button, but a better option is to do it on $('#third').change directly (so the user is saved from one extra button press):
$('#third').change(function() {
$('table tr').filter(function() { // Filters the rows, by:
var number1 = $('#sec').val().split('_')[1]; // comparing the value at #sec
var number2 = $(this).find('td:eq(0)').text().split(' ')[1]; // with the text of the first column.
return number1 == number2;
}).find('td:eq(1)').text($(this).val()); // Updates the second column.
});
Working example at jsFiddle. The only caveat is that, if the user wants to select the first option (the one already selected), he'll have to change it and change again for the event to trigger (in this sense, a select button is cleaner).
if you still want to do that only on button press, just replace $('#third').change(...) with $('#select_btn').click(...) (Edit: and $(this) to $('#third')). You might also have to use event.preventDefault, so the form isn't submitted.

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