- Редактирование таблицы на сайте по клику на ячейку , чтобы в базе данных изменение проявлялось
- Решение
- Create an Editable HTML Table
- Create a Cell in an HTML Table
- Create an Editable Table in HTML
- Conclusion
- Related Article — HTML Table
- Как добавить данные редактирования и удаления в таблицу HTML с помощью JavaScript?
Редактирование таблицы на сайте по клику на ячейку , чтобы в базе данных изменение проявлялось
Здравствуйте ! Помогите юниору
Проблема такова
У меня есть таблица на странице html , которая связана с mysql
Строится она через php
Я хочу чтобы можно было по клику на ячейку , изменять данные
и естественно , чтобы эти данные сохранялись в mysql
Как это можно реализовать , подскажите или может есть уже готовый вариант того , что меня интересует
Подключение к базе данных
require_once("db.php"); if ($connection == false){ echo "Error!"; echo mysqli_connect_errno(); exit(); } ?>
$har = mysqli_query($connection, "SELECT * FROM $dbarticles"); $num_rows = mysqli_num_rows( $har ); ?>
$query = mysqli_query($connection, "SELECT * FROM $dbarticles"); while($row = mysqli_fetch_array($query)){ $id=$row['id']; $name=$row['name']; $second=$row['secondname']; echo " $id $name $second "; } ?>
if(isset($_POST['button'])){ $but = mysqli_query($connection, "INSERT INTO $dbarticles (id) VALUES ($num_rows)"); header("Location: http://**.***.***.**/tablet.html"); ?>
Так же у меня есть скрипт , который я где-то скомуниздил , и он дает мне возможность редактировать таблицу по клику , но он не синхронизирует данные с базой данных , поэтому может здесь надо что-то поковырять ?если можно обойтись без явы , то я буду только рад потому что ничерта не понимаю
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
let table = document.getElementById('table'); let editingTd; table.onclick = function(event) { // 3 возможных цели let target = event.target.closest('.edit-cancel,.edit-ok,td'); if (!table.contains(target)) return; if (target.className == 'edit-cancel') { finishTdEdit(editingTd.elem, false); } else if (target.className == 'edit-ok') { finishTdEdit(editingTd.elem, true); } else if (target.nodeName == 'TD') { if (editingTd) return; // уже редактируется makeTdEditable(target); } }; function makeTdEditable(td) { editingTd = { elem: td, data: td.innerHTML }; td.classList.add('edit-td'); // td в состоянии редактирования, CSS применятся к textarea внутри ячейки let textArea = document.createElement('textarea'); textArea.style.width = td.clientWidth + 'px'; textArea.style.height = td.clientHeight + 'px'; textArea.className = 'edit-area'; textArea.value = td.innerHTML; td.innerHTML = ''; td.appendChild(textArea); textArea.focus(); td.insertAdjacentHTML("beforeEnd", '); } function finishTdEdit(td, isOk) { if (isOk) { td.innerHTML = td.firstChild.value; } else { td.innerHTML = editingTd.data; } td.classList.remove('edit-td'); editingTd = null;
Реализовать регистрацию и авторизацию на сайте, чтобы логин и пароль хранился в базе данных
Доброго времени суток! Задача по учебе реализовать регистрацию и авторизацию на сайте, что бы.
jEditable редактирование таблицы, как узнать текущую ячейку?
Прикольный плагин, подключил нормально, но как на стороне сервера узнать с какой ячейки пришло.
Изменение стилей таблицы по клику
Здравствуйте, помогите со следующим вопросом: требуется, что бы по клику на клавишу "Просмотр".
Перенос данных из StringGrid1 в StringGrid2 по клику мыши в ячейку
Доброе время суток!) Помогите пожалуйста, надо чтоб по клику мыши в первую таблицу, в любую ячейку.
Сообщение было отмечено justux как решение
Решение
Без явы точно можно обойтись, тем более для веба он широко не используется, а вот без ajax никак, если конечно нужно чтобы все работало без обновления страницы.
На основе 2 запроса из гугла
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
html> head> script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> script> style> .edit{ width: 100%; height: 25px; } .editMode{ border: 1px solid black; } table, th, td { border: 1px solid black; } style> script> $(document).ready(function(){ // Add Class $('.edit').click(function(){ $(this).addClass('editMode'); }); // Save data $(".edit").focusout(function(){ $(this).removeClass("editMode"); var id = this.id; var split_id = id.split("_"); var field_name = split_id[0]; var edit_id = split_id[1]; var value = $(this).text(); $.ajax({ url: 'handler.php',//файл с php скриптом, обновляющий данные в бд type: 'post', data: { field:field_name, value:value, id:edit_id },// отправляем имя поля, новое значение и id, чтобы определить, что конкретно и как надо обновить в таблице success:function(response){ console.log('Save successfully'); } }); }); }); script> head> body> div class='container'> table> tr> th>Idth> th>Usernameth> th>Nameth> tr> tr> td>1td> td contentEditable='true' class='edit' id='username_1'>vasya_usertd> td contentEditable='true' class='edit' id='name_1'>vasyatd> tr> tr> td>2td> td contentEditable='true' class='edit' id='username_2'>petya_usertd> td contentEditable='true' class='edit' id='name_2'>petyatd> tr> table> div> body> html>
$field= $_POST['field']; $value = $_POST['value']; $id = $_POST['id']; //подключаемся к бд $con = mysqli_connect('localhost', 'root', 'mypassword','mydatabase'); //делаем запрос на обновление строки $query = "UPDATE `mytable` SET `".$field."`='".$value."' WHERE `id`=".$editid; mysqli_query($con,$query);
Create an Editable HTML Table
- Create a Cell in an HTML Table
- Create an Editable Table in HTML
- Conclusion
This article will discuss creating HTML tables and how to make their cells editable.
Create a Cell in an HTML Table
When creating web pages, sometimes we might need to create tables for data representation. HTML provides us the table attribute to achieve that.
The syntax to create a cell in a table is as below.
table> tr> td>This is a celltd> tr> table>
html lang="en"> head> meta charset="UTF-8"> link rel="stylesheet" href="styles.css"> title>HTML Tabletitle> head> body> table> tr> td>This is a celltd> tr> table> body> html>
As you can see, we retrieved a table with one cell. But it is displayed as plain text because we have not given any style to it.
Let’s add some styles to the cell.
table background-color: rgb(139, 220, 247); width: auto; > td border: 1px solid #000000; text-align: center; padding: 16px; >
In the above output, we can now see it as a table cell.
Create an Editable Table in HTML
On some occasions, users might need to change the content of the cells of a table.
The HTML table element provides the contenteditable property where users can create editable cells. Using this, we can easily edit a table cell.
The syntax to make a cell editable using the contenteditable attribute is as follows.
We can give true or false as the value of the contenteditable attribute. The cell can be editable if the value is true , whereas we can’t edit the cell if the value is false .
Let’s see how we can do that using the previous example with the same styles. You can change the data of the cell accordingly.
table> tr> td contenteditable="true">This is a celltd> tr> table>
As a result, we can have an editable cell as below. To edit the cell, we can double-click on it.
Now, let’s observe what happens when we give false as the value of the contenteditable attribute.
table> tr> td contenteditable="false">This is an editable celltd> tr> table>
As you can see, the data or content of the table is no longer editable. Both true and false values are important on different occasions.
Some developers create forms and other stuff using tables. Sometimes some data needs to remain as they are, and that’s where the developers can use the false value.
If there are data that a user can change, as in the above example, we can use the true option.
Now, let’s make a table where we can use both true and false .
For example, let’s assume a lecturer wants a table on a web page to store the data of three students, and we will implement it. He needs Student ID , Name , and Grade as column headers, and the data we add under the Name and Grade columns must be editable.
The reason is he might type the name inaccurately. Also, the grades may need to be changed because students might ask for re-corrections.
Let’s create a table using the following code chunk.
table> tr> th>Student IDth> th>Nameth> th>Gradeth> tr> tr> td>001td> td>Simon Nicktd> td>Atd> tr> tr> td>002td> td>John Robberttd> td>Ctd> tr> tr> td>007td> td>Chris Hendersontd> td>Btd> tr> table>
We can see the table cells separately by adding some styles to the table.
table background-color: beige; font-family: arial, sans-serif; border-collapse: collapse; width: 50%; > td, th border: 1px solid #dddddd; text-align: left; padding: 8px; >
Now, our table looks more evident than before.
Our next step is to set editable cells. Let’s add contenteditable attributes to the relevant cells with relevant values as below.
table> tr> th>Student IDth> th>Nameth> th>Gradeth> tr> tr> td contenteditable="false">001td> td contenteditable="true">Simon Nicktd> td contenteditable="true">Atd> tr> tr> td contenteditable="false">002td> td contenteditable="true">John Robberttd> td contenteditable="true">Ctd> tr> tr> td contenteditable="false">007td> td contenteditable="true">Chris Hendersontd> td contenteditable="true">Btd> tr> table>
As in the above code, we have set contenteditable attributes with the true values to all the cells related to Name and Grade .
Now, if we run the above code, all the cells except the Student ID cells will be editable as below.
Output When Editing the Names and Grades :
Output When Trying to Edit the Student ID Cells:
As you can see, we can’t edit the Student ID cells because the value of the contenteditable is false .
Conclusion
In this article, we have discussed how to create an HTML table and how to make that table editable using some examples. Also, we learned how to use contenteditable attributes along with the values: true and false .
If you want an editable cell, assign true as the value, and if you don’t need that feature, set false as the value or remove the attribute.
We can make cells editable using JavaScript, but this is a simple way to achieve the goal.
Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.
Related Article — HTML Table
Как добавить данные редактирования и удаления в таблицу HTML с помощью JavaScript?
Программирование и разработка
В веб-разработке часто необходимо обрабатывать данные в таблице HTML. JavaScript предлагает надежные возможности для динамического включения, изменения и удаления данных в таблице. Эти функции позволяют манипулировать содержимым таблицы без необходимости обновления всей страницы, что обеспечивает беспрепятственное и эффективное взаимодействие с пользователем.
HTML-таблица используется для представления табличных данных на веб-странице. Он состоит из строк и столбцов, организованных в виде сетки. Таблицы обычно используются для отображения данных в структурированном виде, например, в финансовых отчетах, списках продуктов и расписаниях. В этой статье мы создадим пример того, как добавлять, редактировать и удалять строки таблицы в Javascript.
Подход: следующий подход будет использоваться для создания динамической таблицы для добавления или удаления строки, а также для редактирования данных в строке таблицы:
- Метод addData()получает данные из полей ввода и создает новую строку в таблице, содержащую предоставленную информацию.
- Кнопка «Редактировать» запускает функцию editData(), которая заменяет ячейки таблицы имени и адреса электронной почты предварительно заполненными полями ввода. Текст кнопки меняется на «Сохранить», и при нажатии вызывается функция saveData().
- Функция saveData()сохраняет отредактированные данные, извлекая входные значения, обновляя ячейки таблицы, сбрасывая кнопку и повторно вызывая editData().
- При нажатии кнопки «Удалить» функция deleteData() удаляет связанную строку из таблицы.
Пример: в этом примере мы увидим, как добавлять редактирование и удалять данные в таблице HTML с помощью JavaScript. Сначала мы принимаем ввод от пользователя, а затем любые данные, введенные пользователем, отображаются в таблице.