Я пытаюсь создать веб-страницу с таблицей ввода, где пользователи могут добавлять или удалять строки по своему усмотрению. Пользовательский интерфейс, как это-
А вот и мой код html
:
<div class = "container my-5">
<h2>Welcome to dynamic input table with row adding option</h2>
<form method = "" action = "">
<table class = "table table-hover my-5">
<thead class = "">
<tr>
<th>No</th>
<th>Name</th>
<th>Pnone Number</th>
<th>Email</th>
<th>Remove?</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><input type = "text" name = "name-1"></td>
<td><input type = "text" name = "phone-1"></td>
<td><input type = "text" name = "Email-1"></td>
<td><i class = "fa fa-times-circle" style = "font-size: 22px; color: red;"></i></td>
</tr>
<tr>
<td>2</td>
<td><input type = "text" name = "name-2"></td>
<td><input type = "text" name = "phone-2"></td>
<td><input type = "text" name = "Email-2"></td>
<td><i class = "fa fa-times-circle" style = "font-size: 22px; color: red;"></i></td>
</tr>
<tr>
<td>3</td>
<td><input type = "text" name = "name-3"></td>
<td><input type = "text" name = "phone-3"></td>
<td><input type = "text" name = "Email-3"></td>
<td><i class = "fa fa-times-circle" style = "font-size: 22px; color: red;"></i></td>
</tr>
<tr>
<td>4</td>
<td><input type = "text" name = "name-4"></td>
<td><input type = "text" name = "phone-4"></td>
<td><input type = "text" name = "Email-4"></td>
<td><i class = "fa fa-times-circle" style = "font-size: 22px; color: red;"></i></td>
</tr>
</tbody>
</table>
<div class = "row m-0">
<button class = "btn btn-warning">Add row</button>
<button class = "btn btn-danger ml-3">Delete last row</button>
<button type = "Submit" class = "btn btn-primary ml-auto">Submit</button>
</div>
</form>
</div>
<head>
<title></title>
<!-- media query support -->
<meta name = "viewport" content = "width=device-width, initial-scale=1, minimum-scale=1" />
<!-- Latest compiled and minified CSS -->
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<!-- font awsome css link -->
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
Теперь моя проблема заключается в том, как я могу реализовать функциональность кнопки Add row
, кнопки Delete last row
и кнопки remove
. И все должно работать таким образом, чтобы я мог использовать это и для отправки данных в бэкенде. Я предпочитаю использовать Django
и MongoDB
для реализации моего бэкенда. Теперь, пожалуйста, помогите мне с лучшим способом реализации этого. Если он может быть реализован с помощью js во внешнем интерфейсе с помощью js, это будет очень полезно для меня, или если он должен быть реализован в бэкэнде с динамическим подходом, он также будет работать.
да, спасибо за предложение, все сделано
Ваш вопрос состоит из многих частей и должен быть разбит на несколько вопросов. Вот простой способ удаления строк. Вместо того, что я сделал здесь, вы захотите сделать кнопку для нажатия. И вы также захотите сделать вызов ajax, чтобы удалить фактические данные в вашей базе данных. Это просто интерфейсный код, визуально показывающий пользователю, что строка была удалена.
$('.my-5 tr').click(function(){
$(this).remove();
return false;
});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "container my-5">
<h2>Welcome to dynamic input table with row adding option</h2>
<form method = "" action = "">
<table class = "table table-hover my-5">
<thead class = "">
<tr>
<th>No</th>
<th>Name</th>
<th>Pnone Number</th>
<th>Email</th>
<th>Remove?</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><input type = "text" name = "name-1"></td>
<td><input type = "text" name = "phone-1"></td>
<td><input type = "text" name = "Email-1"></td>
<td><i class = "fa fa-times-circle" style = "font-size: 22px; color: red;"></i></td>
</tr>
<tr>
<td>2</td>
<td><input type = "text" name = "name-2"></td>
<td><input type = "text" name = "phone-2"></td>
<td><input type = "text" name = "Email-2"></td>
<td><i class = "fa fa-times-circle" style = "font-size: 22px; color: red;"></i></td>
</tr>
<tr>
<td>3</td>
<td><input type = "text" name = "name-3"></td>
<td><input type = "text" name = "phone-3"></td>
<td><input type = "text" name = "Email-3"></td>
<td><i class = "fa fa-times-circle" style = "font-size: 22px; color: red;"></i></td>
</tr>
<tr>
<td>4</td>
<td><input type = "text" name = "name-4"></td>
<td><input type = "text" name = "phone-4"></td>
<td><input type = "text" name = "Email-4"></td>
<td><i class = "fa fa-times-circle" style = "font-size: 22px; color: red;"></i></td>
</tr>
</tbody>
</table>
<div class = "row m-0">
<button class = "btn btn-warning">Add row</button>
<button class = "btn btn-danger ml-3">Delete last row</button>
<button type = "Submit" class = "btn btn-primary ml-auto">Submit</button>
</div>
</form>
</div>
Спасибо большое, может отлично визуально удалить любую ячейку. Но как я могу также добавить ячейку?
А еще я стараюсь избегать ajax, так как не очень хорошо разбираюсь в асинхронной разработке бэкенда. Нет ли более простого способа сделать это?
Вы можете создать свою таблицу динамически, если хотите выполнять такие операции, как добавление и удаление.
Вы можете проверить демо здесь: https://jsbin.com/pewexibole/edit?html,js,console,output
HTML:
<head>
<title></title>
<!-- media query support -->
<meta name = "viewport" content = "width=device-width, initial-scale=1, minimum-scale=1" />
<!-- Latest compiled and minified CSS -->
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<!-- font awsome css link -->
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<div class = "container my-5">
<h2>Welcome to dynamic input table with row adding option</h2>
<table class = "table table-hover my-5">
<thead class = "">
<tr>
<th>No</th>
<th>Name</th>
<th>Pnone Number</th>
<th>Email</th>
<th>Remove?</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class = "row m-0">
<button class = "btn btn-warning" onclick = "addRow()">Add row</button>
<button class = "btn btn-danger ml-3">Delete last row</button>
<button type = "Submit" class = "btn btn-primary ml-auto">Submit</button>
</div>
</div>
JS:
let i = 0;
function rowTemplate(i) {
return `<tr data-index=${i}>
<td>${i}</td>
<td><input type = "text" name = "name-${i}"></td>
<td><input type = "text" name = "phone-${i}"></td>
<td><input type = "text" name = "Email-${i}"></td>
<td><i class = "fa fa-times-circle" style = "font-size: 22px; color: red;" onclick = "removeRow(${i})"></i></td>
</tr>`
}
for (i = 0; i < 4; i ++) {
$('tbody').append(rowTemplate(i));
}
function removeRow(i) {
$("tbody").find(`tr[data-index='${i}']`).remove();
}
function addRow() {
$('tbody').append(rowTemplate(i));
i++;
}
большое спасибо, Ity работает отлично, теперь у меня только один вопрос; Для доступа вводятся данные из бэкенда, по какому имени мне его называть?
Я не понимаю вашего вопроса, вы хотите получить данные из строк и отправить их на сервер?
да, как я могу отправить все данные в бэкэнд? обычно я использую для отправки данных почтовым методом и получаю их по имени в Django. Здесь может быть каждый массив содержимого поля. как я могу получить к ним доступ из бэкэнда?
Можете ли вы сделать свой код исполняемым фрагментом? Если это так, я обновлю свой ответ, чтобы сделать его более полезным для вас.