Как отправить данные в форму html из строки при нажатии на нее
у меня есть таблица с данными и при нажатии на кнопку "редактировать" открывается страница уже с заполненными данные из той строки, на которой была нажата кнопка "Редактировать", но можно ли как то сделать чтобы было без кнопки, а просто при нажатии на строку. Вот код с кнопкой:
$content = '<table>
<thead>
<tr>
<th>Название</th>
<th>Адрес</th>
<th>ИНН</th>
<th>КПП</th>
<th>Расчетный счет</th>
<th>ОГРН</th>';
if ($user_role === 'Администратор' || $user_role === 'Специалист'){
$content .= '<th>Действия</th>';
}
$content .= '</tr>
</thead>
<tbody>';
foreach ($organizations as $organization){
$content .= '<tr>
<td>' . htmlspecialchars($organization['okopf'] ?? '') .' '.'"'. htmlspecialchars($organization['name']) . '"'.'</td>
<td>' . htmlspecialchars($organization['address']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['inn']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['kpp']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['settlement_account']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['ogrn']) . '</td>';
if ($user_role === 'Администратор' || $user_role === 'Специалист'){
$content .= '<td class="th-center">
<form method="POST" action="organizations/edit_organizations.php" >
<input type="hidden" name="action" value="edit_f">
<input type="hidden" name="id" value="' . $organization['id'] . '">
<button type="submit" class="action-button">Редактировать</button>
</form>
</td>';
}
$content .= '</tr>';
}
$content .= '</tbody>
</table>';
Но я смог убрать кнопку и сделать чтобы можно было нажимать на строку с помощью jQuery, но форма не отправляет id данной строки и соответственно данные со строки автоматически не вставляются как это было с кнопкой. Подскажите пож-та как мне сделать чтобы при нажатие на кнопку отправлялась форма? Вот код без кнопки:
$content = '
<table>
<thead>
<tr>
<th>Название</th>
<th>Адрес</th>
<th>ИНН</th>
<th>КПП</th>
<th>Расчетный счет</th>
<th>ОГРН</th>';
$content .= '</tr>
</thead>
<tbody>';
foreach ($organizations as $organization){
$content .= '<tr data-href="../organizations/edit_organizations.php" style="cursor: pointer">
<td>' . htmlspecialchars($organization['okopf'] ?? '') .' '.'"'. htmlspecialchars($organization['name']) . '"'.'</td>
<td>' . htmlspecialchars($organization['address']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['inn']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['kpp']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['settlement_account']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['ogrn']) . '</td>
<form method="POST" action="../organizations/edit_organizations.php" >
<input type="hidden" name="action" value="edit_f">
<input type="hidden" name="id" value="' . $organization['id'] . '">
</form>';
$content .= '</tr>';
}
$content .= '</tbody>
</table>';
Нашел еще один способ сделать просто через javascript, при котором при нажатии на строку tr отправлять форму, но единственная проблема что функция отрабатывает только 1 раз, из-за малого опыта не знаю как заставить отправлять функцию n-количество раз (строки всегда будут меняться) Вот код.
<table>
<thead>
<tr>
<th>Название</th>
<th>Адрес</th>
<th>ИНН</th>
<th>КПП</th>
<th>Расчетный счет</th>
<th>ОГРН</th>';
$content .= '</tr>
</thead>
<tbody>';
foreach ($organizations as $organization){
$content .= '<tr data-href="../organizations/edit_organizations.php" style="cursor: pointer" id="post">
<td>' . htmlspecialchars($organization['okopf'] ?? '') .' '.'"'. htmlspecialchars($organization['name']) . '"'.'</td>
<td>' . htmlspecialchars($organization['address']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['inn']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['kpp']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['settlement_account']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['ogrn']) . '</td>
<form method="POST" action="../organizations/edit_organizations.php" id="formpost">
<input type="hidden" name="action" value="edit_f">
<input type="hidden" name="id" value="' . $organization['id'] . '">
</form>';
$content .= '</tr>';
}
$content .= '</tbody>
</table>';
Вот скрипт.
<script>
document.getElementById("post").onclick = function() {
document.getElementById("formpost").submit();
}
</script>
Ответы (2 шт):
Зачем при клике по строке лишние переходы на другие страницы? Можно всё сделать в одной странице, например по клику на строку открывать "всплывашку" с формой, редактировать, сохранять, и закрывать всплывашку.
А можно ещё проще - по клику на строку превращать её в форму и показывать кнопку сохранения. По кнопке вызывать обработчик события, который сам посредством fetch() отправляет данные в бэк.
Вот данный пример (генерацию страницы на PHP я убрал, чтоб работало).
Стили оформил так, чтобы поля форм казались текстом, а при фокусировке выглядели как форма.
document.getElementById("forms-container").addEventListener('submit', sendForm);
function sendForm(e) {
e.preventDefault()
console.log(e)
//e.target будет содержать нужную форму
let fd = new FormData(e.target)
fetch("save_organization.php", {
method: 'POST',
body: fd
}).then(response=>{
console.log(response)
//Тут обработка ответов
});
}
* {
box-sizing: border-box;
}
table {
border-collapse: collapse;
background: #eee;
width: 90%;
td,
th {
border: 1px solid #ccc;
}
input {
border: 0;
background: #eee;
font-family: serif;
font-size: 1em;
width: 100%;
}
button {
display: none;
}
tr:focus,
tr:has(*:focus, *:active) {
td {
background: #fff;
}
input {
border: 1px solid #777;
background: #fff;
}
button {
display: block;
}
}
}
<table cellspacing=0>
<thead>
<tr>
<th>Название</th>
<th>Адрес</th>
<th>ИНН</th>
<th>КПП</th>
<th>Расчетный счет</th>
<th>ОГРН</th>
<th>Действия</th>
</tr>
</thead>
<tbody id="forms-container">
<tr tabindex=1>
<form>
<td><input type=hidden name=id value=1><input name=name type=text value="Рога и копыта"></td>
<td><input name=address type=text value="Луна, 8"></td>
<td><input name=inn type=text value="123456789"></td>
<td><input name=kpp type=text value="321654"></td>
<td><input name=rs type=text value="456"></td>
<td><input name=ogrn type=text value="555555"></td>
<td><button type=submit>Save</button></td>
</form>
</tr>
<tr tabindex=1>
<form>
<td><input type=hidden name=id value=2><input name=name type=text value="Рога и копыта"></td>
<td><input name=address type=text value="Луна, 8"></td>
<td><input name=inn type=text value="123456789"></td>
<td><input name=kpp type=text value="321654"></td>
<td><input name=rs type=text value="456"></td>
<td><input name=ogrn type=text value="555555"></td>
<td><button type=submit>Save</button></td>
</form>
</tr>
</tbody>
</table>
В вашем последнем примере каждой строке вы назначаете id="post"
, а каждой вложенной форме id="formpost"
(которые, вообще-то, должны быть уникальными в рамках одной страницы), поэтому неудивительно, что ваш код срабатывает только для первой строки таблицы (при этом, скорее всего, ругаясь в консоли DevTools на неуникальность соответствующих id).
Вы можете попробовать генерировать такую же таблицу с использованием классов вместо идентификаторов:
...
$content .=
'<tr data-href="../organizations/edit_organizations.php" style="cursor: pointer" class="post">
<td>' . htmlspecialchars($organization['okopf'] ?? '') .' '.'"'. htmlspecialchars($organization['name']) . '"'.'</td>
<td>' . htmlspecialchars($organization['address']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['inn']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['kpp']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['settlement_account']) . '</td>
<td class="th-center">' . htmlspecialchars($organization['ogrn']) . '</td>
<form method="POST" action="../organizations/edit_organizations.php" class="formpost">
<input type="hidden" name="action" value="edit_f">
<input type="hidden" name="id" value="' . $organization['id'] . '">
</form>';
...
После чего попробовать применить к ней следующий JavaScript-код:
// Перебираем все элементы с классом 'post'
document.querySelectorAll('.post').forEach(function(post) {
// Для каждого элемента 'post' назначаем обработчик клика
post.onclick = function() {
this.querySelector('.formpost').submit();
};
});