DataTables is a powerful jQuery plugin for creating for displaying information in tables and adding interactions to them. It provides searching, sorting and pagination without any configuration. In this article you will learn the basics of DataTables and use it in your website.
1. First create a HTML Table so that the column names are under thead and column data under tbody.
<table id="table_id">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
<tbody>
<tr>
<td>data-1a</td>
<td>data-1b</td>
<td>data-1c</td>
</tr>
<tr>
<td>data-2a</td>
<td>data-2b</td>
<td>data-2c</td>
</tr>
<tr>
<td>data-3a</td>
<td>data-3b</td>
<td>data-3c</td>
</tr>
<tr>
<td>data-4a</td>
<td>data-4b</td>
<td>data-4c</td>
</tr>
.....
</tbody>
</table>
2. Then add the jQuery and DataTables scripts reference on the page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
3. Finally inside the
jQuery .ready()
function call the.DataTable()
function for the table.
<script>
$(document).ready(function () {
$('#table_id').DataTable();
});
</script>
Now let me create a DataTables that shows the Name, Age, Sex & Occupation of 15 people.
The HTML
table’s code is given below:
<table id="table1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Sex</th>
<th>Occupation</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ram</td>
<td>21</td>
<td>Male</td>
<td>Doctor</td>
</tr>
<tr>
<td>Mohan</td>
<td>32</td>
<td>Male</td>
<td>Teacher</td>
</tr>
<tr>
<td>Rani</td>
<td>42</td>
<td>Female</td>
<td>Nurse</td>
</tr>
<tr>
<td>Johan</td>
<td>23</td>
<td>Female</td>
<td>Software Engineer</td>
</tr>
<tr>
<td>Shajia</td>
<td>39</td>
<td>Female</td>
<td>Farmer</td>
</tr>
<tr>
<td>Jack</td>
<td>19</td>
<td>Male</td>
<td>Student</td>
</tr>
<tr>
<td>Hina</td>
<td>30</td>
<td>Female</td>
<td>Artist</td>
</tr>
<tr>
<td>Gauhar</td>
<td>36</td>
<td>Female</td>
<td>Artist</td>
</tr>
<tr>
<td>Jacky</td>
<td>55</td>
<td>Female</td>
<td>Bank Manager</td>
</tr>
<tr>
<td>Pintu</td>
<td>36</td>
<td>Male</td>
<td>Clerk</td>
</tr>
<tr>
<td>Sumit</td>
<td>33</td>
<td>Male</td>
<td>Footballer</td>
</tr>
<tr>
<td>Radhu</td>
<td>40</td>
<td>Female</td>
<td>Coder</td>
</tr>
<tr>
<td>Mamta</td>
<td>49</td>
<td>Female</td>
<td>Student</td>
</tr>
</tbody>
</table>
Next add the necessary jQuery code scripts:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#table1').DataTable();
});
</script>
This is how the jQuery DataTables will look and work.
To set the paging size use the ‘pageLength’ property
$('#table2').DataTable({
"pageLength": 3
});
In the above code block I have set the size as 3. If you do not put the pageLength property in the DataTables then the default page length value of 10 will be applied.
You can bind DataTables
with an array
.
Let’s see how to do it.
<table id="table2">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Sex</th>
<th>Occupation</th>
</tr>
</thead>
</table>
For binding with an array, set the data property to the array name. The below code does this thing.
var array = [
[
"Ram",
"21",
"Male",
"Doctor"
],
[
"Mohan",
"32",
"Male",
"Teacher"
],
[
"Rani",
"42",
"Female",
"Nurse"
],
[
"Johan",
"23",
"Female",
"Software Engineer"
],
[
"Shajia",
"39",
"Female",
"Farmer"
]
];
$('#table2').DataTable({
data: array,
"pageLength": 3
});
You can also bind the DataTables
with a JSON
. Here you have to set the fields
of the JSON
to the columns property of DataTables
.
Check the below code:
<table id="table3">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Sex</th>
<th>Occupation</th>
</tr>
</thead>
</table>
var json = [
{
"name": "Ram",
"age": "21",
"sex": "Male",
"occupation": "Doctor"
},
{
"name": "Mohan",
"age": "32",
"sex": "Male",
"occupation": "Teacher"
},
{
"name": "Rani",
"age": "42",
"sex": "Female",
"occupation": "Nurse"
},
{
"name": "Johan",
"age": "23",
"sex": "Female",
"occupation": "Software Engineer"
},
{
"name": "Shajia",
"age": "39",
"sex": "Female",
"occupation": "Farmer"
}
];
$('#table3').DataTable({
data: json,
columns: [
{ data: 'name' },
{ data: 'age' },
{ data: 'sex' },
{ data: 'occupation' }
],
"pageLength": 3
});
With jQuery DataTables you can also make AJAX request to file for APIs. Here I make an AJAX
request to get data from a JSON
file, and then I will show that file’s data in my DataTables
My JSON file is named as data.json
, and is shown below:
{
"roomsData": [
{
"id": 1,
"room": "Basic",
"price": "$49"
},
{
"id": 2,
"room": "Common",
"price": "$59"
},
{
"id": 3,
"room": "Luxury",
"price": "$99"
},
{
"id": 4,
"room": "Deluxe",
"price": "$89"
},
{
"id": 5,
"room": "Super",
"price": "$199"
}
]
}
Now to make AJAX request to this file use the ajax property of DataTables and specify the url
of the json
file to it.
Also note that I don’t have to make separate jQuery AJAX Method call here, as ajax
property of the DataTables is doing that work for me.
The binding with AJAX
code is given below.
<table id="table4">
<thead>
<tr>
<th>Id</th>
<th>Room</th>
<th>Price</th>
</tr>
</thead>
</table>
$('#table4').DataTable({
ajax: {
url: 'data.json',
dataSrc: "roomsData"
},
columns: [
{ data: 'id' },
{ data: 'room' },
{ data: 'price' }
],
"pageLength": 3
});
Categories : jQuery
tricor online order tricor drug fenofibrate over the counter
buy ketotifen no prescription capsules ziprasidone 80mg order generic tofranil 25mg
order minoxidil sale buy cheap generic flomax online ed medications
order acarbose online purchase repaglinide online cheap fulvicin 250 mg drug
aspirin sale generic levoflox 250mg imiquad sale
melatonin drug melatonin pill cost danocrine
dydrogesterone 10mg brand dydrogesterone pill jardiance online buy
purchase florinef online florinef pills loperamide for sale online
buy prasugrel 10mg sale dramamine drug purchase detrol pills
order mestinon 60 mg online cheap piroxicam buy online buy maxalt paypal
ferrous sulfate 100 mg pills order ferrous sulfate 100mg buy sotalol online
purchase xalatan eye drop capecitabine 500 mg ca buy rivastigmine 6mg generic
order vasotec sale how to buy casodex order lactulose for sale
premarin uk premarin 0.625mg for sale us viagra sales
omeprazole 10mg sale cheap prilosec 20mg lopressor 50mg brand
cheap cialis online cost tadalafil generic sildenafil 50mg
telmisartan cheap hydroxychloroquine 400mg pill order generic molnupiravir 200 mg
cenforce ca buy cenforce pill where to buy aralen without a prescription
order provigil 200mg for sale phenergan price buy deltasone 40mg online
buy accutane generic amoxil 500mg us purchase zithromax pill
order cefdinir 300 mg generic order generic omnicef 300 mg lansoprazole 15mg ca
Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind write my assignment updating your blog with more information? It is extremely helpful for me.
Very informative post! There is a lot of information here that can help any business get started with a successful social networking campaign Arctic Mads Mikkelsen Red Shearling Coat and we are providing advanced analytics and data management services
order azithromycin 500mg generic gabapentin 600mg without prescription buy gabapentin 600mg online cheap
purchase lipitor online cheap order norvasc generic purchase amlodipine online
free spins no deposit usa free casino games no registration no download buy generic furosemide over the counter
recommended you read recommended you read albuterol 2mg sale
pantoprazole 20mg pill buy pantoprazole 20mg generic buy phenazopyridine 200 mg online cheap
free slot play synthroid uk buy levoxyl online cheap
generic symmetrel buy atenolol 100mg online dapsone cost
clomiphene online buy azathioprine without a prescription order imuran 25mg pill
buy medrol 8 mg online buy generic aristocort over the counter aristocort oral
buy vardenafil sale order levitra cost zanaflex
oral dilantin 100 mg buy generic oxybutynin 5mg order oxytrol without prescription
coversum online buy desloratadine medication buy fexofenadine 180mg without prescription
purchase baclofen online toradol online buy buy cheap ketorolac
order baclofen 10mg generic order amitriptyline generic toradol ca
claritin 10mg price tritace buy online priligy 30mg pill
order fosamax 70mg pill oral furadantin buy nitrofurantoin 100mg online
propranolol without prescription buy motrin 600mg generic order plavix without prescription
purchase pamelor sale methotrexate 2.5mg uk buy panadol 500 mg
amaryl pills order generic misoprostol buy generic arcoxia for sale
buy medex online buy warfarin 2mg sale reglan online buy
Быстромонтажные здания: финансовая выгода в каждой составляющей! В современной действительности, где время равно деньгам, сооружения с быстрым монтажем стали реальным спасением для фирм. Эти новаторские строения обладают твердость, экономичность и молниеносную установку, что сделало их наилучшим вариантом для разных коммерческих начинаний. Быстровозводимые здания работы 1. Ускоренная установка: Секунды - самое ценное в коммерции, и сооружения моментального монтажа позволяют существенно сократить время монтажа. Это особенно выгодно в условиях, когда срочно нужно начать бизнес и начать монетизацию. 2. Финансовая экономия: За счет улучшения производственных процедур элементов и сборки на объекте, стоимость быстровозводимых зданий часто оказывается ниже, чем у традиционных строительных проектов. Это позволяет сэкономить средства и достичь более высокой инвестиционной доходности. Подробнее на http://scholding.ru В заключение, объекты быстрого возвода - это великолепное решение для коммерческих инициатив. Они обладают быстроту монтажа, экономичность и надежные характеристики, что позволяет им лучшим выбором для профессионалов, стремящихся оперативно начать предпринимательскую деятельность и получать доход. Не упустите шанс на сокращение времени и издержек, превосходные экспресс-конструкции для вашего предстоящего предприятия!
Экспресс-строения здания: коммерческая выгода в каждой детали! В современной действительности, где время имеет значение, экспресс-конструкции стали реальным спасением для компаний. Эти новаторские строения комбинируют в себе высокую прочность, экономическую эффективность и быстрое строительство, что сделало их наилучшим вариантом для различных бизнес-проектов. Каркас быстровозводимого здания из металлоконструкций цена 1. Высокая скорость возвода: Секунды - самое ценное в экономике, и скоростроительные конструкции позволяют существенно уменьшить временные рамки строительства. Это высоко оценивается в ситуациях, когда требуется быстрый старт бизнеса и начать получать доход. 2. Финансовая экономия: За счет улучшения процессов изготовления элементов и сборки на объекте, стоимость быстровозводимых зданий часто бывает менее, чем у традиционных строительных проектов. Это обеспечивает экономию средств и обеспечить более высокий доход с инвестиций. Подробнее на http://www.scholding.ru/ В заключение, быстровозводимые здания - это первоклассное решение для бизнес-мероприятий. Они включают в себя молниеносную установку, экономическую эффективность и повышенную надежность, что делает их идеальным выбором для предпринимательских начинаний, ориентированных на оперативный бизнес-старт и выручать прибыль. Не упустите возможность сократить издержки и сэкономить время, наилучшие объекты быстрого возвода для ваших будущих проектов!
order xenical 120mg pill buy diltiazem 180mg pills order diltiazem
famotidine usa tacrolimus 1mg cost prograf 5mg for sale
order esomeprazole 40mg order topamax sale topamax for sale
brand azelastine 10ml buy avapro generic irbesartan drug
buy imitrex cheap imitrex 50mg for sale oral avodart
buy allopurinol generic temovate usa buy crestor
order ranitidine generic celecoxib 200mg sale celebrex 100mg drug
buspar tablet buspar pills buy cordarone generic
order flomax 0.2mg online cheap buy flomax pills brand zocor 10mg
order motilium 10mg sale sumycin tablet buy sumycin pill
spironolactone 25mg for sale order valacyclovir pills finpecia over the counter
dissertation assistance do my term paper buy essay paper
buy fluconazole pills for sale buy diflucan 200mg sale ciprofloxacin buy online
sildenafil 100mg brand order sildenafil 50mg without prescription estrace 1mg generic
buy metronidazole 200mg pills order bactrim 960mg generic order keflex 125mg generic
buy generic lamictal for sale lamotrigine 200mg drug nemazole canada
cleocin where to buy erythromycin 500mg drug fildena 100mg pill
order nolvadex 20mg betahistine 16mg for sale buy generic symbicort
tretinoin gel canada purchase tadalis generic buy avana 100mg for sale
ceftin 500mg sale order bimatoprost eye drops how to buy methocarbamol
tadalafil 10mg tablet buy generic indocin 75mg indocin 75mg ca
trazodone oral order trazodone 50mg pill clindac a online order
buy aspirin 75 mg online burton brunette free poker online
buy generic terbinafine over the counter order lamisil 250mg generic casino games online real money
buy my essay online gambling for real money casino card games
buy thesis paper personal statement writing help buy suprax 200mg online cheap
calcitriol 0.25 mg sale tricor ca purchase tricor pill
buy amoxicillin for sale buy biaxin online cheap cost clarithromycin
progesterone only pill for acne best acne treatment teenage guys purchase oxcarbazepine for sale
catapres 0.1 mg usa spiriva 9mcg uk buy tiotropium bromide 9mcg generic
buy alfuzosin 10mg alternative painkiller to co codamol heartburn medications over the counter
purchase minocin sale buy minocin 50mg sale cost ropinirole
top 10 sleeping pills nz buy sleeping pills uk online best online weight loss prescription
buy femara generic aripiprazole ca abilify over the counter
nhs stopping smoking service meds online without a prescription pain medications online pharmacies
provera 10mg pills buy generic provera online microzide 25 mg tablet
online doctor prescription valtrex how quick does valacyclovir work new fda approved drugs 2023
periactin 4mg tablet purchase fluvoxamine pill ketoconazole pill
lamisil for toenail fungus reviews genital herpes daily medication consumer reports blood pressure medication
purchase cymbalta online glipizide 10mg generic buy provigil 100mg pills
how to calm down gastritis vaughan williams classification drugs uti antibiotics cost without insurance
promethazine buy online purchase stromectol for sale ivermectin for cov 19
online birth control refill for hims premature ejaculation treatment how to last longer pills
drugs to reduce stomach acid best probiotic supplement for gerd medication for flatulence australia
buy prednisone 10mg pill prednisone order online amoxil 1000mg cheap
buy urso no prescription buy zyban 150mg online cheap buy cetirizine 10mg pill
azithromycin price order gabapentin 100mg pill neurontin cheap
strattera online atomoxetine generic zoloft 100mg tablet
escitalopram 10mg us buy generic prozac for sale buy generic revia
furosemide cost furosemide order online purchase ventolin pill
order combivent 100 mcg pills order ipratropium 100mcg generic order linezolid 600 mg sale
order starlix generic order capoten pill purchase atacand online
order augmentin 1000mg amoxiclav price purchase serophene without prescription
nateglinide 120 mg sale brand atacand candesartan 8mg pills
buy tegretol cheap buy tegretol 400mg pills buy generic lincomycin over the counter
order vardenafil 10mg sale levitra for sale hydroxychloroquine 400mg pill
oral cenforce 100mg buy glycomet without a prescription order glycomet 500mg generic
buy cefadroxil 500mg generic how to buy ascorbic acid epivir pills
lipitor 10mg uk zestril 5mg canada buy zestril
buy prilosec 20mg generic lopressor canada buy atenolol 50mg
buy dostinex online buy claritin online cheap buy dapoxetine 60mg
buy depo-medrol without a prescription triamcinolone online order desloratadine 5mg brand
buy misoprostol paypal buy generic misoprostol over the counter order generic diltiazem
buy nootropil pills for sale nootropil over the counter buy cheap anafranil
buy zovirax 800mg without prescription buy rosuvastatin without a prescription crestor 20mg pills
sporanox 100mg for sale order prometrium 200mg sale generic tindamax
purchase zetia generic order generic sumycin 500mg brand tetracycline 500mg
order olanzapine 10mg sale zyprexa pills buy generic diovan for sale
buy cyclobenzaprine 15mg for sale buy flexeril sale purchase toradol sale
colchicine ca buy methotrexate 2.5mg buy methotrexate 10mg without prescription
best pimple medication for teenagers order prednisolone 10mg without prescription will pimple get wase when taking fulcin
best generic allegra buy generic medrol over the counter types of allergy pills
medicine that helps with puking cipro 1000mg sale
order sleeping tablets online uk phenergan cost
generic deltasone 5mg prednisone tablet
nsaid with least stomach problems heartburn over the counter remedies
prescription acne medication for adults purchase absorica online strongest prescription acne medication
homeopathic medicine for stomach acid how to buy zyloprim
buy accutane pill buy accutane 40mg pill isotretinoin pill
buy amoxicillin 500mg pills amoxicillin 1000mg cost amoxicillin 1000mg cheap
order zithromax 250mg sale order azithromycin 500mg sale buy zithromax 250mg online cheap
oral neurontin 600mg gabapentin tablet
azithromycin 500mg pill buy azithromycin 250mg pills buy azithromycin 250mg online
lasix online buy order lasix online
purchase omnacortil without prescription purchase prednisolone online buy prednisolone 20mg generic
vibra-tabs pills monodox medication
buy ventolin pills ventolin online buy albuterol 4mg over the counter
brand amoxiclav how to buy clavulanate
buy levothyroxine online cheap synthroid generic levothyroxine generic
buy levitra 10mg pill levitra 20mg uk
generic zanaflex buy zanaflex sale tizanidine drug
order generic clomiphene serophene tablet order clomiphene online
cost prednisone 5mg buy deltasone prednisone 10mg cheap
order semaglutide online cheap generic rybelsus 14 mg buy rybelsus 14mg online
generic accutane 20mg absorica pills isotretinoin 10mg over the counter
order semaglutide 14mg pill buy generic rybelsus 14mg buy semaglutide without a prescription
cheap amoxil generic order amoxil 500mg online amoxil tablet
buy asthma pills onlin purchase albuterol inhaler albuterol cheap
buy zithromax 500mg generic buy azithromycin 500mg online purchase azithromycin generic
augmentin pill oral augmentin augmentin 625mg ca
order omnacortil 40mg without prescription omnacortil 10mg pills cheap omnacortil sale
semaglutide order online rybelsus pill semaglutide 14 mg price
crazy poker games online roulette game us blackjack online
purchase pregabalin online lyrica 75mg us purchase lyrica online cheap
buy vardenafil 20mg pills buy generic vardenafil vardenafil 20mg brand
order triamcinolone 4mg online cheap aristocort pill aristocort 4mg uk
buy hydroxychloroquine for sale order plaquenil plaquenil order
order desloratadine 5mg pill clarinex 5mg canada where to buy clarinex without a prescription
buy generic tadalafil 5mg cialis for sale cialis on line
buy generic claritin 10mg claritin 10mg ca buy claritin 10mg pills
purchase cenforce pill cenforce online order cenforce oral
priligy buy online dapoxetine 30mg drug misoprostol where to buy
orlistat without prescription order diltiazem 180mg diltiazem online buy
buy metformin buy glucophage 500mg without prescription order metformin online
order zovirax 800mg pills purchase zovirax generic buy generic zyloprim for sale
order generic amlodipine 10mg norvasc 10mg over the counter norvasc 5mg usa
buy generic rosuvastatin buy ezetimibe 10mg sale ezetimibe 10mg uk
buy lisinopril 10mg online cheap buy lisinopril 10mg sale how to get zestril without a prescription
motilium for sale online tetracycline 500mg brand order tetracycline
buy prilosec without a prescription buy generic prilosec buy omeprazole 10mg
cyclobenzaprine us lioresal us ozobax tablet
metoprolol 100mg uk buy lopressor online cheap buy metoprolol 100mg sale
order toradol 10mg without prescription buy cheap gloperba buy colcrys without prescription
buy atenolol no prescription tenormin 100mg canada atenolol price
Наша бригада опытных исполнителей готова выдвинуть вам актуальные средства, которые не только обеспечат надежную защиту от прохлады, но и подарят вашему домашнему пространству стильный вид. Мы работаем с новейшими составами, подтверждая долгосрочный период службы и замечательные результаты. Утепление внешней обшивки – это не только экономия энергии на огреве, но и забота о окружающей природе. Энергосберегающие методы, каковые мы производим, способствуют не только зданию, но и поддержанию природы. Самое важное: Утепление дома снаружи цена за м2 у нас составляет всего от 1250 рублей за квадратный метр! Это доступное решение, которое превратит ваш дом в действительный уютный корнер с небольшими тратами. Наши работы – это не лишь теплоизоляция, это составление пространства, в где каждый член отразит ваш свой модель. Мы примем во внимание все твои пожелания, чтобы преобразить ваш дом еще еще более удобным и привлекательным. Подробнее на https://www.ppu-prof.ru Не откладывайте занятия о своем жилище на потом! Обращайтесь к спецам, и мы сделаем ваш жилище не только уютнее, но и по последней моде. Заинтересовались? Подробнее о наших трудах вы можете узнать на нашем сайте. Добро пожаловать в мир гармонии и качественной работы.