title

Create Editable HTML table with source code

This jQuery code will make the cell editable on double-click. To use the code, simply add class to the table cell and put the above jQuery in the head.

$(function () < $("td").dblclick(function () < var OriginalContent = $(this).text(); $(this).addClass("cellEditing"); $(this).html(" " + OriginalContent + " "); $(this).children().first().focus(); $(this).children().first().keypress(function (e) < if (e.which == 13) < var newContent = $(this).val(); $(this).parent().text(newContent); $(this).parent().removeClass("cellEditing"); >>); $(this).children().first().blur(function()< $(this).parent().text(OriginalContent); $(this).parent().removeClass("cellEditing"); >); >); >);

Editable Cell in HTML table using Ajax

$(this).children().first().keypress(function (e) < if (e.which == 13) < var fullContent = $(this).val(); $(this).parent().html(fullContent); $(this).parent().removeClass("cellEditing"); //Call the server side file to communicate with database. var URL = '/callfile.php' ; //alert (URL); var xmlhttp; if (window.XMLHttpRequest)< // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); >else < // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); >xmlhttp.onreadystatechange=function() < // if successfully done it will return status 200 if (xmlhttp.readyState==4 && xmlhttp.status!=200)< alert ('Can not update comment. Contact admin') >> xmlhttp.open("GET",URL,true); xmlhttp.send(); > >);

Add/Delete rows in HTML table using Javascript

If you want to add or delete a row in the table on click you can use append() functions.

$('button').live('click' , function(event)< var $row = (" 6 class6 school6 "); $('#example').append($row); >);

There are scenarios where we have the whole row from one table to another. This example will show how you can add a row in first table and remove it from second table.

$('#example tbody tr td').live('click' , function(event)< var $row = $(this).closest('tr'); $(this).closest("tr").remove(); // remove row $('#example2').append($row); >); $('#example2 tbody tr td').live('click' , function(event)< var $row = $(this).closest('tr'); $(this).closest("tr").remove(); // remove row $('#example').append($row); >);

Javascript to get table content in the form on mouse click

If you need to get all table contents in the form to edit, you can use the below javascript code.

$(document).ready(function() < $('#htmlgrid tbody tr td').on('click', 'a', function(event)< var first_cell = $('td:eq(0)', $(this).parent().parent()).text(); var second_cell = $('td:eq(1)', $(this).parent().parent()).text(); var third_cell = $('td:eq(2)', $(this).parent().parent()).text(); var answer = prompt('Please enter your Password', ''); if (answer!=null)< answer=$.trim(answer); answer=answer.toUpperCase(); password = $.trim(answer); password_from_db = password_from_db() if(password==password_from_db)< document.forms[0].elements['first_cell'].value = first_cell; document.forms[0].elements['second_cell'].value = second_cell; document.forms[0].elements['third_cell'].value = third_cell; >> else < alert('wrong_password'); >>); >);

Hiding table row using jQuery

There are many ways to hide table rows. You can either use jQuery or CSS.
This is jQuery code that will hide the first and second th and td of the table.

Читайте также:  Syncworld java util prefs filesystempreferences

To hide table row using CSS you can use «display: none»

Single checkbox functionality for table rows.

check/uncheck all checkbox in HTML table

Drag and Drop rows from one table to another

This example shows the drag and drop of one row from the first table to the second table.

CSS code for drag and drop in HTML table

ul li < min-width: 200px; >.dragging li.ui-state-hover < min-width: 240px; >.dragging .ui-state-hover a < color:green !important; font-weight: bold; >th,td < text-align: right; padding: 2px 4px; border: 1px solid; >.connectedSortable tr, .ui-sortable-helper < cursor: move; >.connectedSortable tr:first-child < cursor: default; >.ui-sortable-placeholder

jQuery code for Drag and Drop HTML table

$(document).ready(function() < $tabs = $(".tabbable"); $('.nav-tabs a').click(function(e) < e.preventDefault(); $(this).tab('show'); >) $( "tbody.connectedSortable" ) .sortable( < connectWith: ".connectedSortable", items: ">tr:not(:first)", appendTo: $tabs, helper:"clone", zIndex: 999990, start: function()< $tabs.addClass("dragging") >, stop: function() < $tabs.removeClass("dragging") >>) .disableSelection() ; var $tab_items = $( ".nav-tabs > li", $tabs ).droppable(< accept: ".connectedSortable tr", hoverClass: "ui-state-hover", over: function( event, ui ) < var $item = $( this ); $item.find("a").tab("show"); >, drop: function( event, ui ) < return false; >>); >);

Источник

Create a Table With jQuery

Create a Table With jQuery

  1. Create a Table With jQuery by Taking the Table Content as a String
  2. Create a Table With jQuery by Creating a Table Instance

With the help of the jQuery library, we can add new table rows to our content and create the table element. We will go for basic loop work to ensure our data or output pattern is stacked in a table format.

We will examine two examples, one that will take the table tags and contents as a string. Later on, appending it will configure it as a table in the HTML body.

However, creating table elements as strings can hamper later customization. So, in our second example, we will create an instance of a table element, and thus by specifying the attributes ( id , class ), we can change the table contents properties.

Let’s give a thorough check to understand.

Create a Table With jQuery by Taking the Table Content as a String

Here, we will take a variable to store the table elements start tag, add the contents, and the end tag. In the next step, we will append this sum or collection of strings to the div we considered.

The basic problem would be we are unable to reinitialize the properties for table data or table rows. Let’s check the code lines.

script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous">script> div id="tab"> div> script>  var content = "" for(i=0; i3; i++)  content += ''; >  content += "
' + 'output ' + i + '
"
$('#tab').append(content); script>

Create Table by Taking Table Content as String

Create a Table With jQuery by Creating a Table Instance

We will consider creating the instance for a table along with its id and class attribute. Later, based upon preference, we can change the properties.

The code fences describe this more explicitly.

script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous">script> div id="tab"> div> script>  var table = $('');  for(i=0; i3; i++)  var row = $('').text('output ' + i).addClass('rows');  row.addClass('rows').css('color':'red'>);  table.append(row);  >   $('#tab').append(table);  script> 

Create Table by Creating Table Instance

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

Related Article — jQuery Table

Источник

Руководство: использование jQuery Table плагина — делаем таблицу удобной

Работа с таблицами в WEB-интерфейсе может быть намного удобнее работы в том же Excel`е. Можно организовать пользовательские элементы самостоятельно, но зачем? Одна строка JS кода и подключенный плагин — готово.

Плагин jQuery Table — это профессиональный инструмент для работы с HTML-таблицами. Он обладает огромным функционалом, который включает в себя:

  • Сортировку по любому столбцу;
  • Быстрый поиск по таблице;
  • Пагинацию;
  • Лимит на отображение кол-ва элементов;
  • Адаптивный дизайн таблицы.

Особенно хочется отметить, адаптивный дизайн таблицы HTML — это извечная проблема для верстальщика. Спору нет, загонять контент в ячейки и позиционировать их без «ползания», весьма удобно. Однако, когда речь идет о просмотре таблицы на мобильном устройстве, то здесь начинаются проблемы. Порой, неразрешимые.

Итак, пришло время ознакомиться с тем, как нам преобразовать таблицу. Готовый результат можно посмотреть здесь. Скачиваем архив из источника, либо подключаем файлы CSS и JS через ресурс CDN:

И давайте начнем с самого простого примера, допустим, имеем следующую HTML-таблицу:

 
Name Position Office Age Start date Salary
Name Position Office Age Start date Salary
Tiger Nixon System Architect Edinburgh 61 2011/04/25 $320,800
Garrett Winters Accountant Tokyo 63 2011/07/25 $170,750

И без какого-либо CSS-кода, объявляем нашу таблицу в скриптах:

В данном случаем, Вы получите все параметры таблицы по-умолчанию. В большинстве вариантах, этих настроек бывает достаточно. Однако, данный плагин jQuery Table не был таким популярным, если бы не обладал потрясающей гибкостью. Отключаем сортировки и пагинацию:

Все просто и корректно работает. Давайте организуем сортировку по-умолчанию по любому необходимому полю:

где, «order» : [[ 3, «desc» ]] — это третий (с 0) столбец и по убыванию. Скрываем колонки и убираем из быстрого поиска:

Таблица с горизонтальной прокруткой:

Очень удобно также указывать и языковые настройки:

Конечно, одним из полезных свойств плагина является его поддержка технологии AJAX:

просто указываем текстовый файл, где будут располагаться массивы со столбцами вида:

[ "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$3,120" ]

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

Все полезные ссылки находятся на странице источника. Там же Вы можете задать вопрос автору плагина. Удачи!

Источник

Editable HTML Table Using Javascript/Jquery With Add Edit Delete Rows

editable html table using jquery

Every Web Developer and Content Creator need to use HTML Tables each time, They need to show some data in table structure, all thanks modern web technologies, nowadays web has become more dynamic and people are not interested in those boring static websites and in this web How to Tutorial we are going to use modern javascript, jquery and Twitter Bootstrap power to make Our HTML Tables Dynamic and Cool Looking in other words How to add, edit and delete rows of a HTML table with jQuery/Javascript. So let’s learn how to create editable HTML table.

What you’ll be able to do after finishing this tutorial:

  • Create Editable HTML Table Using Javascript, Jquery, and Bootstrap With Add, Edit, and Delete Features.
  • add, edit and delete rows of an HTML table with jQuery or Javascript.
  • Add, Edit, And Delete Rows From Table Dynamically Using Power of JavaScript.
  • Editable Dynamic HTML Table which can be edited offline

We will be using bootstrap frontend framework to make things look prettier on the frontend.

    create a static HTML table using bootstrap with dummy data or your data.

 
Full Name WebSite Contact No
John M http://john-m.com 9876543210
Ariana Smith https://araiana-smith.com 1234567890
Silver Bourne https://silver-bourne.com 988889888
Rahul Ray https://rahul-ray.com 9797979797
          
Full Name WebSite Contact No
John M http://john-m.com 9876543210
Ariana Smith https://araiana-smith.com 1234567890
Silver Bourne https://silver-bourne.com 988889888
Rahul Ray https://rahul-ray.com 9797979797
$('#DyanmicTable').SetEditable(< $addButton: $('#add_new-row') >); //if you to alert or do something after edit, delete then use following functions onEdit: function() <>, //Edit event onDelete: function() <>, //Delete event onAdd: function() <> //Add event
         
Tutorial | StackFAME Homepage

Dynamic Editable HTML Table using Javascript, Jquery and Bootstrap with add, edit, and Delete Options


Full Name WebSite Contact No
John M http://john-m.com 9876543210
Ariana Smith https://araiana-smith.com 1234567890
Silver Bourne https://silver-bourne.com 988889888
Rahul Ray https://rahul-ray.com 9797979797

editable html table using jquery

Conclusion:

This shows how easy javascript has made life of web developers and modern web applications.if you have any queries, please comment below and don’t forget to subscibe to our newsletter for awesome freebies and articles every week.

5 thoughts on “Editable HTML Table Using Javascript/Jquery With Add Edit Delete Rows”

Thank you so much , i want to check validation and change events (warn about invalid input or
prevent invalid changes on an keyup event if the input values match with regular expressions ( like noun , average, field, …)) and get data from mysql table and display it instead of defined values using php, how can i melt all this please Reply

you’ll have to persist data in some kind of backend or localstorage and retrieve it on page load. Reply

Hi Sam,
you can make use of OnEdit, OnAdd and onDelete functions to achieve this to persist changes in backend or json. Reply

Источник

Оцените статью