У меня есть рабочий скрипт, который пользователь заполняет входы в форме и когда они отправляют форму, а содержимое входов формы вводится как строка таблицы.Создать идентификатор строки для динамической таблицы JS
Есть ли какой-либо способ, я думаю, в JS, чтобы каждая строка имела уникальный идентификатор и добавляла кнопку удаления к последнему столбцу каждой строки, чтобы пользователь мог удалить отдельную строку.
Спасибо за спасение жизни !!!!
HTML Форма
<form id="my_form" action="table_form.php" method="post">
<div style="width:10%; float:left;">
Quantity<br />
<input name="field_1" type="text" id="field_1" size="3" />
</div>
<div style="width:20%; float:left;">
Part Number<br />
<input type="text" id="field_2" name="field_2" />
</div>
<div style="width:30%; float:left;">
Notes<br />
<input name="field_3" type="text" id="field_3" size="45" />
</div>
<div style="width:20%; float:left;">
Unit Price<br />
<input type="text" id="field_4" name="field_4" />
</div>
<div style="width:20%; float:left;">
<br />
<input type="submit" value="Add Row" />
</div>
</form>
<!--
Here we create our HTML table.
Note the ID of the table. This will be used in our javascript file
Our table only contains a header row. All other content will be added dynamically
--><? $rowid = 1; ?>
<table width="100%" id="my_table">
<tbody id="my_table_body">
<tr>
<th width="5%"><div align="left">Qty</div></th>
<th width="19%"><div align="left">Part Number</div></th>
<th width="46%"><div align="left">Notes</div></th>
<th width="15%"><div align="left">Unit Price</div></th>
<th width="15%"><div align="left">Row Total</div></th>
</tr>
</tbody>
</table>
JS
window.addEvent('domready', function(){
$('my_form').addEvent('submit', function(e){
e.stop();
this.set('send', {
onComplete: function(response){
var data = JSON.decode(response);
inject_row($('my_table_body'), data);
}
});
var valid_form = true;
$$('#my_form input').each(function(item){
if(item.value == '') valid_form = false;
});
if(valid_form) {
this.send();
} else {
alert('Fill in all fields');
}
});
var inject_row = function(table_body, data){
var row_str = '<tr width="100%">';
data.each(function(item, index){
row_str += '<td>'+item+'</td>';
});
row_str += '<td><input type="submit" name="deleterow" id="deleterow" value="Delete" /></td></tr>';
var newRow = htmlToElements(row_str);
newRow.inject(table_body);
}
var htmlToElements = function(str){
return new Element('div', {html: '<table><tbody>' + str + '</tbody></table>'}).getElement('tr');
}
});
PHP
<?php
/**
* If nothing is being posted to this script redirect to
* our HTML page.
*/
if(! $_POST){
header('Location: newquote.php');
}
// create an empty array for our results
$results = array();
/**
* Stick the values from _POST into our results array
* while also stripping out any html tags
*
* This is where you would perform any required processing
* of the form data such as server side validation or updating
* a database.
*/
foreach($_POST as $field){
$results[] = strip_tags($field);
}
// Echo our results as a JSON encoded string.
echo json_encode($results);
?>
«добавить кнопку удаления до последней Colum каждой строки, так что пользователь может удалить отдельную строку» - Как сохранить вам данные на стороне сервера ? Где выполняется эта операция удаления? Серверный? Сторона клиента? И то и другое? – VolkerK
Ничего не хранится SS - и операция будет проходить CS.Добавление кнопки удаления довольно прямолинейно, она дает строке уникальный идентификатор, поэтому пользователь может удалять только соответствующую строку при нажатии кнопки удаления. Спасибо, что посмотрели. – 2009-07-28 16:15:04
Bifter, вам не нужны никакие идентификаторы. Когда нажата кнопка, просто переместите DOM к ближайшему элементу TR и «удалите» его ... – James