WebListEditor

редактируемая таблица

Ребята помоги разобраться с созданием редактируемой таблицы. Нужно создать таблицу с редактируемыми ячейками. По щелчку на ячейку открывалась форма редактирования в самой ячейке,для первого столбца получается, а как сделать для другого не знаю.


require_once("scripts/dbdata.php");
?>














$res = mysql_query("SELECT * FROM listitems");
if ($res === FALSE) echo "Ошибка при отправке запроса к БД:".mysql_error();
>
elseif (mysql_num_rows($res) == 0) echo "
";
>
else ?>

Справочник пользователей:



$i = 0;
while ($item = mysql_fetch_array($res, MYSQL_ASSOC)) $i++;

?>










id="itemId_">

id="utemId_">
"onclick='closeOtherEditors(" + editors.length +
")' >" +
data.value + "

" +
" data.id + ")'>"alt='Удалить' title='Удалить' />");
//создаем редактор для нового элемента и добавляем его в массив
editors.push(addEditor("itemId_" + data.id, data.id));
//подсвечиваем вставленный элемент
var items = $$('#list li');
new Effect.Highlight(items.last(),
);
>
else //выводим сообщение об ошибке
var form = $('add_item_form');
new Insertion.After(form, "

data.error_mes + "

");
>
>

//эта функция удаляет элемент списка
function deleteItem(id) var pars = $H().toQueryString();
new Ajax.Request(
"scripts/delete.php",
onSuccess:function(transport) var data = eval('(' + transport.responseText + ')');
//удаляем элемент из списка
var listElem = $('itemId_' + data.deletedId).parentNode.getAttribute('id');
Element.remove(listElem);
var listNum = listElem.substring(8);
//обновляем номера у всех остальных записей
var nodes = $$('#list li');
nodes.each(
function(node, index) if (index >= listNum) node.setAttribute('id', 'listNum_' + index);
var innerNodes = $A(node.getElementsByTagName('div'));
innerNodes[0].innerHTML = index + 1;
innerNodes[1].setAttribute("onclick", "closeOtherEditors(" + index + ")");
>
>
);
//удаляем редактор из массива
editors.splice(listNum,1);
>>
);
>

function closeOtherEditors(curEditor) editors.each(
function(editor, index) if (index != curEditor) editor.leaveEditMode();
>
>
);
>

Источник

Редактируемая таблица

Редактируемая таблица

Сегодня я расскажу как сделать редактируемые зоны сайта, которые можно изменять не прибегая к помощи визуальных редакторов и редакторов кода.

Задача - сделать максимально интуитивный интерфейс для редактирования. Я буду показывать на примере таблицы, но эту технику можно приспособить (изменив пару строк) для любых блочных элементов, вплоть до body (хотя тут смысла уже мало).

Приступим. Есть таблица, программер и пользователь. Пользователь не знает и знать не хочет html. Программер очень ленится делать админку с визуальным редактором, а потом чистить код, полученный от этого редактора. И есть таблица, которую должен редактировать пользователь.

Я хочу чтобы при клике на ячейке таблицы, появлялось текстовое поле с содержимым этой ячейки. А при уходе фокуса с этого поля, его текущее содержимое становилось содержимым ячейки.

Конечно, эта задача решается на JavaScript. И конечно я буду использовать горячо любимый мной jQuery.

Круто. Оно даже работает. Поля появляются. Но не исчезают. Для того, чтобы они исчезали, нужно вешать на событие blur еще один обработчик. Причем делать это нужно каждый раз, как мы генерируем поле. Поэтому дописываем.

Теперь все работает. Почти. Глюки начинаются когда мы тыкаем по самому полю. Событие click для ячейки тоже срабатывает. Поэтому мы получаем код поля редактирования и вставляем его в поле редактирования. Такая вот рекурсия. Чтобы этого не происходило, нужно отлавливать элемент, по которому происходит клик.

Все. Теперь при кликах на разные поля таблицы, мы будем получать текстовые поля, заполнив которые, можно редактировать таблицу. Примерно такой интерфейс у всеми нами любимых табличных редакторов вроде Excel или Calc. Нативней не придумаешь, пожалуй.

Единственное, что мне хотелось бы изменить - возможность сохранения изменений по Enter. Нет ничего проще.

На снятии фокуса у нас уже есть обработчик, который делает что нужно.

Вот что у нас получилось. Тыцкайте на ячейки.

Куда развиваться

Этот скрипт, конечно, можно развить для конкретных нужд. Например, можно править не только ячейки, но и блоки div. Можно приспособить к этой же идее переписывание src у картинок. На ум сразу приходит, что нужно бы привязываться не к имени блока, а к специальному классу. Например, редактировать разрешать только элементы с классом editable. Если смотреть дальше, то можно сделать дополнительные классы ed-text и ed-line и по ним определять рисовать ли input или textarea.

Как сохранить результат - думаю понятно. Нужно при помощи того же JavaScript взять весь измененный контент и каким-либо образом отправить на сервер, где скрипт знает что с этим делать. Я бы просто использовал метод $.post().

Лично я при помощи такого нехитрого метода сделал интерфейс, при помощи которого специальный человек может редактировать большую таблицу. Это гораздо проще и эффективней, чем если бы он присылал мне аналог этой таблицы в Excel или говорил в какую по счету ячейку что вставить.

Если вам понравилась идея и вы считаете что при помощи нее сможете решить свою задачу - используйте ее смело. А если использовать ее самостоятельно не получается - обращайтесь ко мне.

Источник

Create an Editable HTML Table

Create an Editable HTML Table

  1. Create a Cell in an HTML Table
  2. Create an Editable Table in HTML
  3. 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

Источник

Читайте также:  How to convert string to string in javascript
Оцените статью