I'm building a site using CakePHP and am currently working on adding data to two separate tables at the same time.. not a problem.
The problem I have is that I'm looking to dynamically alter the form that accepts the input values, allowing the click of a button/link to add an additional row of form fields.
At the moment I have a table that looks something like this:
<table>
<thead>
<tr>
<th>Campus</th>
<th>Code</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select id="FulltimeCourseCampusCode0CampusId" name="data[FulltimeCourseCampusCode][0][campus_id]">
<option value=""></option>
<option value="1">Evesham</option>
<option value="2">Malvern</option>
</select>
</td>
<td>
<input type="text" id="FulltimeCourseCampusCode0CourseCode" name="data[FulltimeCourseCampusCode][0][course_code]">
</td>
</tr>
</tbody>
What I need is for the row within the tbody tag to be replicated, with the minor change o开发者_JAVA技巧f having all the zeros (i.e. such as here
FulltimeCourseCampusCode0CampusIdand here
data[FulltimeCourseCampusCode][0][campus_id]) incremented.
I'm very new to jQuery, having done a few minor bits, but nothing this advanced (mostly just copy/paste stuff).
Can anyone help?
I have created a plugin for jQuery that might help you, it's simple to use. http://boriscy.github.com/grider/
This will work:
$('#add').click(function() {
var index = $('table tbody tr').last().index() + 1;
var tr = $('table tbody tr').first().clone();
tr.find('select')
.attr('id', 'FulltimeCourseCampusCode' + index + 'CampusId')
.attr('name', 'data[FulltimeCourseCampusCode][' + index + '][campus_id]');
tr.find('input')
.attr('id', 'FulltimeCourseCampusCode0CourseCode')
.attr('name', 'data[FulltimeCourseCampusCode][' + index + '][course_code]');
$('table tbody').append(tr);
return false;
});
Write a function that returns the HTML (as a string or a DOM tree) but give it a parameter for the index.
This should work. If you execute the following every time the user clicks the add button. But no guarantee (untested written in 1min)
var rows = $("table tbody tr");
var first rows.eq(0);
first.clone().appendTo($("table tbody")).find("*[id^=FulltimeCourseCampusCode]").each(function() {
var $this = $(this);
$this.attr("id", $this.attr("id").replace("0", rows.size()));
$this.attr("name", $this.attr("name").replace("0", rows.size()));
})
精彩评论