How can I use a mask in values came from database? - javascript

I'm getting some data from my database and wanted to format it inside my view.
My code is simple, with a table bringing the data from database, but i want to show my phone with a mask: (12) 94832-3823.
Tried all sort os things, but no success, can anyone give me a hint?
My table code:
<table class="table table-bordered" id="example10" width="100%" cellspacing="0">
<thead>
<tr>
<th>{{ __('messages.serial no')}}</th>
<th>{{ __('messages.Delivery_Boy')}}</th>
<th>{{ __('messages.Delivery_Boy_Image')}}</th>
<th>{{ __('messages.Delivery_Boy_Phone')}}</th>
<th>{{ __('messages.Status')}}</th>
<th>{{ __('messages.action')}}</th>
</tr>
</tfoot>
<tbody>
#if(count($delivery_boy)>0)
#php $i=1; #endphp
#foreach($delivery_boy as $delivery_boys)
<tr>
<td>{{$i}}</td>
<td>{{$delivery_boys->delivery_boy_name}}</td>
<td align="center"><img src="{{url($delivery_boys->delivery_boy_image)}}" style="width: 21px;"></td>
<td>{{$delivery_boys->delivery_boy_phone}}</td>
<td>
#if($delivery_boys->is_confirmed==0)
Yes
No
#elseif($delivery_boys->is_confirmed == 1)
<span style="color:green;">Aprovado</span>
#else
<span style="color:red;">Reprovado</span>
#endif
</td>
<td>
<i class="fa fa-edit" style="width: 10px;"></i>
<button type="button" style="width: 28px; padding-left: 6px;" class="btn btn-danger" data-toggle="modal" data-target="#exampleModal{{$delivery_boys->delivery_boy_id}}"><i class="fa fa-trash"></i></button>
</td>
</tr>
#php $i++; #endphp
#endforeach
#else
<tr>
<td>No data found</td>
</tr>
#endif
</tbody>
</table>
How's it displaying now:
Thanks for your time!

The easiest way would be to remove the php echo phone and replace with hard coded text. Like that <td>xxx-xxx-xxx</td>.
UPDATE
You tagged your question with javascript. Javascript version:
Only important would be the regex pattern. /(\d{2})(\d{5})(\d+)/
javascript example
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '');
var match = cleaned.match(/(\d{2})(\d{5})(\d+)/);
if (match) {
return '(' + match[1] + ') ' + match[2] + '-' + match[3];
}
return null;
}
p = "+5511920140349"
console.log( formatPhoneNumber(p) )
Appendix
Change this line with the phone number from <td>{{$delivery_boys->delivery_boy_phone}}</td> to <td class="phonenumbers">{{$delivery_boys->delivery_boy_phone}}</td>. Now, you have a seelctor and can fetch the lines and modified by js. like that:
const nums = document.querySelectorAll('.phonenumber');
console.log(nums)
nums.forEach(td => {
const p = td.innerHTML;
td.innerHTML = formatPhoneNumber(p)
})
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '');
var match = cleaned.match(/(\d{2})(\d{5})(\d+)/);
if (match) {
return '+(' + match[1] + ') ' + match[2] + '-' + match[3];
}
return null;
}
<table border="1px">
<tr>
<td>abc</td>
<td class="phonenumber">123456789</td>
</tr>
<tr>
<td>abc</td>
<td class="phonenumber">123456789</td>
</tr>
<tr>
<td>abc</td>
<td class="phonenumber">123456789</td>
</tr>
</table>

What you could do with a simple regex replace, is replacing all the digits into a X.
So on the place where you want to show the 'masked' phone number you can place this:
preg_replace('/\d/', 'X', '+5511920140349');

Related

Wanted to display all the row data inside the table BY ID

I wanted to fetch multiple row data in a table by ID but this code throwing all rows. IDK how to do that please review my code and give feedback. And also I attached the output image which I'm getting. I want to display all the row data inside the table where is (शिर्षक डेबिट क्रेडिट) these topics. [1]: https://i.stack.imgur.com/cFo7b.png
----modal-----
<script>
$(document).ready(function() {
$('.view_btn').click(function(e) {
e.preventDefault();
var id = $(this).closest('tr').find('.id').text();
$.ajax({
type: "GET",
url: " {{ route('biniyojan_popup_details') }}",
data: {
'checking_viewbtn': true,
'id': id,
},
//success: function(response){
success: function(data) {
var html = '';
var biniyojan_popup_details = data.biniyojan_popup_details;
if (biniyojan_popup_details.length > 0) {
for (let i = 0; i < biniyojan_popup_details.length; i++) {
html += `
<table border="1" class="table table-hover table-wrapper-scroll-y my-custom-scrollbar">
<thead class="text-white bg-primary" style="font-size: 14px;">
<tr>
<th scope="col">S.N </th>
<th scope="col">मिति </th>
<th scope="col">आ.ब </th>
<th scope="col">स्रोत व्यहोर्ने संस्था</th>
</thead>
<tbody class="bbody" style="font-size: 14px;">
<tr>
<td>` + biniyojan_popup_details\[i\]\['biniyojan_id'\] + `</td>
<td>` + biniyojan_popup_details\[i\]\['date'\] + `</td>
<td>` + biniyojan_popup_details\[i\]\['ab'\] + `</td>
<td>` + biniyojan_popup_details\[i\]\['school'\] + `</td>
</tr>
</tbody>
</table>
<table id="example" border="1" style=" width:50% ; " class="table table-hover table-wrapper-scroll-y my-custom-scrollbar">
<thead class="text-white bg-primary" style="font-size: 14px;">
<tr>
<th>शिर्षक</th>
<th>डेबिट</th>
<th>क्रेडिट</th>
</tr>
</thead>
<tbody class="text-dark" style="font-size: 14px;">
<tr>
<td>` + biniyojan_popup_details\[i\]\['kriyakalap'\] + `</td>
<td id="bujet">` + biniyojan_popup_details\[i\]\['cash'\] + `</td>
</tr>
<tr>
<td>` + biniyojan_popup_details\[i\]\['debit_credit_type'\] + `</td>
<td></td>
<td id="">` + biniyojan_popup_details\[i\]\['cash'\] + `</td>
</tr>
<tr class="text-white bg-secondary" style="font-size: 14px;">
<td style="font-weight:bold;">Total</td>
<td style="font-weight:bold;">` + biniyojan_popup_details\[i\]\['cash'\] + `</td>
<td style="font-weight:bold;">` + biniyojan_popup_details\[i\]\['cash'\] + `</td>
</tr>
</tbody>
</table>
`;
}
} else {
html += `
<tr>
<td colspan = "9" > Data not Found! </td>
</tr>
`;
}
$(".modal-body").html(html);
$('#exampleModalCenter').modal('show');
}
})
});
});
</script>
<!-- Modal Data -->][1]
----Controller-----
public function biniyojan_popup_details()
{
$biniyojan_popup_details = DB::table('biniyojan_details')
->leftJoin('biniyojan','biniyojan.biniyojan_id','biniyojan_details.biniyojan_id')
->get();
return response()->json(\['biniyojan_popup_details' => $biniyojan_popup_details\]);
}
Try this slight change. It adds a '=' to define what type of comparison we're making with biniyojan.biniyojan_id and biniyojan_details.biniyojan_id.
{
$biniyojan_popup_details = DB::table('biniyojan_details')
->leftJoin('biniyojan','biniyojan_details.biniyojan_id','=','biniyojan.biniyojan_id')
->get();
return response()->json(\['biniyojan_popup_details' => $biniyojan_popup_details\]);
}
You can try adding a where clause to your original code or try an alternative method using Models. This code works perfectly for me in my own project and I adapted it to your table names. I think you're trying to get details by an ID.
$biniyojan_popup_details = Biniyojan::where('biniyojan.biniyojan_id','=',$id)
->leftJoin('biniyojan_details','biniyojan.biniyojan_id','=','biniyojan_details.biniyojan_id')
->select('binoyojan_details.*','biniyojan.field1')
->get();

How can this be solved and to get numbers?

var tada =document.querySelectorAll("#element > table tr:nth-child(n+0) td:nth-child(1)")[0].outerText
this gains first
var tada =document.querySelectorAll("#element > table tr:nth-child(n+0) td:nth-child(1)")[1].outerText
This kind of text how can it be changed to fit all the values?
How do I change [0].outerText
0 to all numbers?
or how to get only the first number from the picture (console.log)
They just need to get those first numbers the code of the page looks like this
http://jsfiddle.net/8cuagzjd/1/
and yet how to calculate all array?
This is my approach,
There is a NaN element that I didn´t know if you want to remove or remain there.
The code split the td tag and get the last part (after the div). Then just parseInt() the value and you will get the number.
As a result you will get an array with the numbers.
//just commented this for tests purpose
//var tada = Array.from(document.querySelectorAll("#element > table tr:nth-child(n+0) td:nth-child(1)"));
var tada = Array.from(document.querySelectorAll("table tr:nth-child(n+0) td:nth-child(1)"));
let numbers = [];
tada.forEach(e => {
let num = parseInt(e.innerHTML.split("</div>")[1]);
//to avoid adding Nan
if (!isNaN(num)) numbers.push(num);
});
let sum = numbers.reduce((a, b) => a + b, 0);
console.log(sum);
<div class="trainqueue_wrap" id="trainqueue_wrap_barracks">
<table class="vis" style="width: 100%">
<tbody>
<tr>
<th style="width: 25%">Výcvik</th>
<th>Trvání</th>
<th>Zhotovení</th>
<th style="width: 150px">Ukončení *</th>
<th style="background:none !important; width: 2%"></th>
</tr>
<tr class="lit">
<td class="lit-item">
<div class="unit_sprite unit_sprite_smaller sword"></div>
19 Šermířů
</td>
<td class="lit-item"><span class="">0:00:37</span></td>
<td class="lit-item">dnes v 00:42:11 hodin</td>
<td class="lit-item"><a class="btn btn-cancel" onclick="return TrainOverview.cancelOrder(1645)" href="/">Storno</a></td>
<td class="lit-item" style="background:none !important;"></td>
</tr>
</tbody>
<tbody id="trainqueue_barracks">
<tr class="sortable_row" id="trainorder_0">
<td class="">
<div class="unit_sprite unit_sprite_smaller spear"></div>
20 Kopiníků
</td>
<td>0:00:32</td>
<td>dnes v 00:42:43 hodin</td>
<td><a class="btn btn-cancel" onclick="return TrainOverview.cancelOrder(1646)" href="/">Storno</a></td>
</tr>
<tr class="sortable_row" id="trainorder_1">
<td class="">
<div class="unit_sprite unit_sprite_smaller spear"></div>
20 Kopiníků
</td>
<td>0:00:32</td>
<td>dnes v 00:43:15 hodin</td>
<td><a class="btn btn-cancel" onclick="return TrainOverview.cancelOrder(1647)" href="/">Storno</a></td>
</tr>
<tr>
<td colspan="3"> </td>
<td class="lit-item">
<a class="evt-confirm btn btn-cancel nowrap" data-confirm-msg="Opravdu chceš zrušit veškerou rekrutaci?" href="">Zrušit vše</a></td>
<th style="background:none !important;"></th>
</tr>
</tbody>
</table>
</div>

How to replace text of tds instead of href

i have a table with multiple rows. and i have rows that each of them has a specific class. in the last row i have a link . how can i replace each td text infront of their name in link ?
i wrote the below code but it sets the texts at the end of my links.
here is my snippet :
$(".list").each(function(index, element) {
var route=$(this).closest("tr").find(".route").text()
var airline=$(this).closest("tr").find(".airline").text()
var route=$(this).closest("tr").find(".route").text()
var linkk=$(this).attr("href")
$(this).attr("href",linkk+route+airline+route); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table border="1">
<tr>
<td class="route">tehran-istanbul</td>
<td class="airline">Iran air</td>
<td class="route">Ss 454</td>
<td><p class="date1">1398-5-12</p><p class="date2">(2017-08-23)</p></td>
<td>link</td>
</tr>
<tr>
<td class="route">tehran-Ankara</td>
<td class="airline">Tukish airline</td>
<td class="route">7547</td>
<td><p class="date1">1395-5-12</p><p class="date2">(2018-01-01)</p></td>
<td>link</td>
</tr>
</table>
few issues with your code:
you are redeclaring variable route, will not be helpful in your case, instead initialize two vars route1 and route2.
linkk+route+airline+route won't give the string you need you will need to add extra strings like 'route=' to identify parameters in between.
$(this).parents("tr").find(".route") will give you multiple elements with class route, you need to target specific elements, you can use first() and last() in your case.
$(".list").each(function(index, element) {
var route1= "route=" + $(this).parents("tr").find(".route").first().text();
var airline= "airline=" + $(this).parents("tr").find(".airline").first().text();
var route2= "route=" + $(this).parents("tr").find(".route").last().text();
var date1 = "date1=" + $(this).parents("tr").find(".date1").first().text();
var date2 = "date2=" + $(this).parents("tr").find(".date2").first().text();
var link = $(this).attr("href").replace(/\?.*/g, "?") + route1 + "&" + airline + "&" + route2 + "&" + date1 + "&" + date2;
$(this).attr("href", link);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table border="1">
<tr>
<td class="route">tehran-istanbul</td>
<td class="airline">Iran air</td>
<td class="route">Ss 454</td>
<td><p class="date1">1398-5-12</p><p class="date2">(2017-08-23)</p></td>
<td>link</td>
</tr>
<tr>
<td class="route">tehran-Ankara</td>
<td class="airline">Tukish airline</td>
<td class="route">7547</td>
<td><p class="date1">1395-5-12</p><p class="date2">(2018-01-01)</p></td>
<td>link</td>
</tr>
</table>
Similar to #DiJ I slightly changed the name of one of your arguments (the second route to routeno). And then I basically tried to reduce the code to the minimum, making it simpler at the same time.
$(".list").each(function(index, element) {
['route','airline','routeno'].forEach(function(i,o){console.log(i)});
$(this).closest("tr").find("td").each((i,o)=>{
if (vars.indexOf(o.className)>-1)
this.href+=o.className+'='+encodeURIComponent(o.innerHTML)+'&';
});
this.href+='date1=&date2=';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table border="1">
<tr>
<td class="route">tehran-istanbul</td>
<td class="airline">Iran air</td>
<td class="routeno">Ss 454</td>
<td><p class="date1">1398-5-12</p><p class="date2">(2017-08-23)</p></td>
<td>link</td>
</tr>
<tr>
<td class="route">tehran-Ankara</td>
<td class="airline">Tukish airline</td>
<td class="routeno">7547</td>
<td><p class="date1">1395-5-12</p><p class="date2">(2018-01-01)</p></td>
<td>link</td>
</tr>
</table>
You can do the same also without the indexOf() testing, like
$(".list").each(function(index, lnk) {
var $tr=$(lnk).closest("tr");
['route','airline','routeno'].forEach(function(col,i){
lnk.href+=encodeURIComponent($tr.find("td."+col).text())+'&'; });
lnk.href+='date1=&date2=';
});

Unable to get HTML table rows values using jQuery

I have some HTML that looks as follows:
<table id="resultsTable" class="table table-bordered table-responsive table-hover table-condensed sortable">
<thead>
<tr>
<th>Company Name</th>
<th>Tours Offered</th>
<th>Average Rating</th>
<th>Total Reviews</th>
</tr>
</thead>
<tbody class="searchable">
#foreach (var item in Model.AccommodationList)
{
<tr>
<td class="accommodationName">
#Html.ActionLink(item.AccommodationName, "ViewHomePage", "AccommodationHomepage", new {accommodationId = item.AccommodationId}, null)
</td>
<td>
#Html.DisplayFor(modelItem => item.FormattedAddress)
</td>
<td>
<Deleted for brevity>
</td>
<td>
#Html.DisplayFor(modelItem => item.TotalReviews)
</td>
<td class="latitudeCell" style="display: none;">
#Html.DisplayFor(modelItem => item.Latitude)
</td>
<td class="longitudeCell" style="display: none;">
#Html.DisplayFor(modelItem => item.Longitude)
</td>
</tr>
}
</tbody>
</table>
I am trying to get the value of the accommodation name, latitude and longitude in each row with the following jQuery:
$('#resultsTable tbody tr').each(function () {
var latitude = $(this).find(".latitudeCell").html();
var longitude = $(this).find(".longitudeCell").html();
var accommodationName = $(this).find(".accommodationName").html();
});
}
However I must be doing something incorrectly because I'm not able to get any values.
Use javascript table.rows function and textContent property to get the inner text of the cell like you can do something like below:
for(var i = 1, row; row = table.rows[i]; i++)
{
var col1 = row.cells[0].textContent;
var col2 = row.cells[1].textContent;
} var col3 = row.cells[2].textContent;
Don't use innerText it is much slower than textContent and also doesn't work in firefox.
I wrote up a fiddle and modified some of your code so I could put text in your cells, I am wondering if this will help you? If not could you write up a small fiddle and I can provide some more assistance.
https://jsfiddle.net/y3llowjack3t/8cL94hgq/
$('#resultsTable tbody tr').each(function () {
var latitude = $(this).find(".latitudeCell").html();
var longitude = $(this).find(".longitudeCell").html();
var accommodationName = $(this).find(".accommodationName").html();
alert(latitude);
});
You are getting the data correctly but, you don't seem to do anything with the values you obtain from the table. And, after .each(), you will not have access to even the values from the last row since you're using local variables. You can create an array that has all the data.
Give this a try:
var locations = $('#resultsTable tbody tr').map(function() {
var location = {};
location.latitude = $(this).find(".latitudeCell").html();
location.longitude = $(this).find(".longitudeCell").html();
location.accommodationName = $(this).find(".accommodationName").html();
return location;
}).get();
console.log( locations );
//OUTPUT: [{"latitude": "<val>","longitude": "<val>", "accommodationName": "<val>"},{.....},....]
Your code works for me:
example
In the code you paste you put a } more, try to check if there's some issues with brakets.
Here is a working example. In your example, I did not see how you were calling your function. I enclosed your function in $().ready() so that it is called when the DOM is ready. You will want to call your function any time the tan;e content changes.
$().ready(function() {
$('div#cellValues').empty();
$('div#cellValues').append('<ul></ul>');
$('#resultsTable tbody tr').each(function(index) {
var latitude = $(this).find('.latitudeCell').html();
var longitude = $(this).find(".longitudeCell").html();
var accommodationName = $(this).find(".accommodationName").html();
$('div#cellValues ul').append('<li>' + accommodationName + ': [' + latitude + ',' + longitude + ']</li>');
});
});
#cellValues {
border: 1px solid red;
}
#cellValues::before {
content: "Cell Values:";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cellValues"></div>
<table id="resultsTable" class="table table-bordered table-responsive table-hover table-condensed sortable">
<thead>
<tr>
<th>Company Name</th>
<th>Tours Offered</th>
<th>Average Rating</th>
<th>Total Reviews</th>
</tr>
</thead>
<tbody class="searchable">
<tr>
<td class="accommodationName">accomidationName1</td>
<td>FormattedAddress1</td>
<td></td>
<td>TotalReviews1</td>
<td class="latitudeCell" style="display: none;">Latitude1</td>
<td class="longitudeCell" style="display: none;">Longitude1</td>
</tr>
<tr>
<td class="accommodationName">accomidationName2</td>
<td>FormattedAddress2</td>
<td></td>
<td>TotalReviews2</td>
<td class="latitudeCell" style="display: none;">Latitude2</td>
<td class="longitudeCell" style="display: none;">Longitude2</td>
</tr>
<tr>
<td class="accommodationName">accomidationName3</td>
<td>FormattedAddress3</td>
<td></td>
<td>TotalReviews3</td>
<td class="latitudeCell" style="display: none;">Latitude3</td>
<td class="longitudeCell" style="display: none;">Longitude3</td>
</tr>
</tbody>
</table>

Sorting multiple html tables with multiple sorts

I have several html tables on my page and I want to be able to sort them based on the value of one of their cell values. Here is an example of my tables
<div id="tables">
<table class="sortable">
<tr>
<td>Comic Book Name</td>
<td id="comic">Batman</td>
</tr>
<tr>
<td>Main Character</td >
<td ="character">Bruce Wayne</td>
</tr>
<tr>
<td>Hero Name</td>
<td id="hero">Batman</td>
</tr>
<tr>
<td>Published</td>
<td id="publish">05/01/1940</td>
</tr>
</table>
<table class="sortable">
<tr>
<td>Comic Book Name</td>
<td id="comic">Green Arrow</td>
</tr>
<tr>
<td>Main Character</td >
<td ="character">Oliver Queen</td>
</tr>
<tr>
<td>Hero Name</td>
<td id="hero">Green Arrow</td>
</tr>
<tr>
<td>Published</td>
<td id="publish">11/01/1941</td>
</tr>
</table>
</div>
I am providing the following drop down to allow users to filter.
<select id="OrderBy">
<option selected="selected" value="comic">Comic Name</option>
<option value="character">Character Name</option>
<option value="hero">Hero Name</option>
<option value="publish">Earliest Publish Date</option>
</select>
My hopes here are to sort the tables alphabetically by Comic book name when they choose Comic Name, alphabetically by Character Name when they select character name etc. etc.
Here is the javascript/jquery I have come up with so far. I'm sure this could be done better but I'm new to Javascript and Jquery.
$('#OrderBy').on('change', function () {
_order = $('#OrderBy').val();
switch (_order) {
case "comic":
$('#sortable').sort(function () {
});
break;
case "character":
$('#sortable').children().sort(function (a, b) {
});
break;
case "publish":
$('#sortable').sort(function () {
});
break;
case "publish":
$('#sortable').sort(function () {
if ($(b).children().find('#Hours').text() - $(a).children().find('#publish').text() <= 0) {
return $(a) - $(b);
}
return $(b) - $(a);
});
break;
}
});
Everywhere I look someone suggests Sorttables or tableSorter but I've only seen how they would work for a single table whose rows are being sorted. I know what everyone is thinking at this point, don't use tables this way. My problem is there is already a bunch of jquery and javascript supporting the tables and I'm not experienced enough in the languages to re-write all of that.
I like the idea of pushing everything onto a stack as described here but I always generated an error about how my array/stack was not defined.
First, you should not put several times the same id, but use classes instead:
<div id="tables">
<table class="sortable">
<tr>
<td>Comic Book Name</td>
<td class="comic">Green Arrow</td>
</tr>
<tr>
<td>Main Character</td >
<td class="character">Oliver Queen</td>
</tr>
<tr>
<td>Hero Name</td>
<td class="hero">Green Arrow</td>
</tr>
<tr>
<td>Published</td>
<td class="publish">11/01/1941</td>
</tr>
</table>
<table class="sortable">
<tr>
<td>Comic Book Name</td>
<td class="comic">Batman</td>
</tr>
<tr>
<td>Main Character</td >
<td class="character">Bruce Wayne</td>
</tr>
<tr>
<td>Hero Name</td>
<td class="hero">Batman</td>
</tr>
<tr>
<td>Published</td>
<td class="publish">05/01/1940</td>
</tr>
</table>
</div>
For your problem, I would use the native Array.prototype.sort method
var tables = [];
var $tables = $("table.sortable");
var container = $("#tables");
// this is the only specific case, as the date does not start by the year
// it will be used to sort by publish date
function sortByDate(a, b) {
return new Date(a.publish).getTime() - new Date(b.publish).getTime();
}
function sortTables(order) {
var sort;
if (order === "publish") {
tables = tables.sort(sortByDate);
} else {
tables = tables.sort(function(a, b) {
return a[order] < b[order] ? -1 : 1;
});
}
tables.forEach(function(data,i) {
tables[i].$el.detach()
container.append(tables[i].el);
});
}
function init() {
//populate the tables array that will be sorted
$tables.each(function(i, val) {
var $this = $(this);
tables.push({
$el: $this,
el: this,
comic: $this.find(".comic").text(),
character: $this.find(".character").text(),
hero: $this.find(".hero").text(),
publish: $this.find(".publish").text()
});
});
$("#OrderBy").on("change", function(event) {
sortTables(event.currentTarget.value);
});
//by default sort by Hero
sortTables("hero");
}
init();
Primarily, Sort can't happen when you have data in two different tables. To make it possible, you need to put id to them, not just classes because your primary issue isn't CSS. Again, if you put same id to different contents, it can't be spotted specifically. So, debugged code would be:
<div id="tables">
<table id="tbl1" class="sortable">
<tr>
<td>Comic Book Name</td>
<td class="comic">Batman</td>
</tr>
<tr>
<td>Main Character</td >
<td class="character">Bruce Wayne</td>
</tr>
<tr>
<td>Hero Name</td>
<td class="hero">Batman</td>
</tr>
<tr>
<td>Published</td>
<td class="publish">05/01/1940</td>
</tr>
</table>
<table id="tbl2" class="sortable">
<tr>
<td>Comic Book Name</td>
<td class="comic">Green Arrow</td>
</tr>
<tr>
<td>Main Character</td >
<td class="character">Oliver Queen</td>
</tr>
<tr>
<td>Hero Name</td>
<td class="hero">Green Arrow</td>
</tr>
<tr>
<td>Published</td>
<td class="publish">11/01/1941</td>
</tr>
</table>
Your drop-down menu(filter box) is properly defined. Now, in js code, there are some syntactical mistakes.
like, 'class' identifier is '.', 'id' identifier is '#', you used '#' instead of '.' some places :
switch (_order) {
case "comic":
$('#sortable').sort(function () {});
debugged code would be:
$('#OrderBy').on('change', function () {
_order = $('#OrderBy').val();
switch (_order) {
case "comic":
$('.sortable').sort(function () {});
break;
case "character":
$('.sortable').children().sort(function (a, b) {
});
break;
case "publish":
$('.sortable').sort(function () {
});
break;
case "publish":
$('.sortable').sort(function () {
if ($(b).children().find('#Hours').text() - $(a).children().find('#publish').text() <= 0) {
return $(a) - $(b);
}
return $(b) - $(a);
});
break;
}});
There's no official table sort() function jquery library. It would work for array only, but you won't have any array here.
So we make a sort function on our own. We can name it 'sortTable()'. The code for this should be:
<!-- -------------------------------------------------------------- -->
<!-- Secondary functions -->
<!-- Creates a new table to display the sorted Table -->
function createEmptyTable(){
var outerDiv = document.createElement('div');
outerDiv.setAttribute('id','ResultTable');
var innerTable = doucment.createElement('table');
innerTable.setAttribute('id','sortedTable');
var newRows = new Array();
var recordIndex = document.getElementsByClassName('comic');
innerTable.innerHTML = "<tr> <th>Comic Book Name </th> <th>Main Character</th> <th>Hero Name</th> <th>Published</th> </tr>";
for(var i=0; i<recordIndex.Length;i++){
newRows[i]= document.createElement('tr');
outerDiv.appendChild(innerTable).appendChild(newRows[i]);
}
}
<!-- ------------------------------------------------------------- -->
<!-- function to find out in which table chosen filter belongs -->
function recordSearch(keyWord){
var sortableTables = document.getElementsByClassName('sortable');
for( var i=0; i<sortableTables.length;i++){
if($(sortableTables[i]).find(keyword)){
return sortableTable[i];
}
}
<!-- ------------------------------------------------------------- -->
<!-- Primary function to sort the Table -->
function sortTable(filtered_option){
<!-- first we delete any existing sorted table -->
if(document.getElementById('ResultTable')){
var existingSortedTable = document.getElementbyId('ResultTable');
existingSortedTable.removeChild(document.getElementById('sortedTable');
}
<!-- now we create new table & put the result -->
createEmptyTable();
var comicNames = document.getElementsByClassName('comic');
var characterNames = document.getElementsByClassName('character');
var heroNames = document.getElementsByClassName('hero');
var publishDates = document.getElementsByClassName('publish');
switch (filtered_option) {
case 'comic' :
var sortedComicNames = comicNames.sort();
for(var i=0;i<sortedComicNames.length;i++){
var foundRecord = recordSearch(sortedComicNames[i]);
var allFields = foundRecord.getElementByTagName('tr').getElementsByClassName('td');
var emptyRows = document.getElementById('sortedTable').getElementsByTagName('tr');
for(var j=0;j<allFields.length;j++){
emptyRows[i+1].innerHTML = "<td>" + allFields[j].value + "</td>" ;
}}
break;
case 'character' :
var sortedCharacterNames= characterNames.sort();
for(var i=0;i<characterNames.length;i++){
var foundRecord = recordSearch(sortedCharacterNames[i]);
var allFields = foundRecord.getElementByTagName('tr').getElementsByClassName('td');
var emptyRows = document.getElementById('sortedTable').getElementsByTagName('tr');
for(var j=0;j<allFields.length;j++){
emptyRows[i+1].innerHTML = "<td>" + allFields[j].value + "</td>" ;
}}
break;
case 'hero' :
var sortedHeroNames= heroNames.sort();
for(var i=0;i<heroNames.length;i++){
var foundRecord = recordSearch(heroNames[i]);
var allFields = foundRecord.getElementByTagName('tr').getElementsByClassName('td');
var emptyRows = document.getElementById('sortedTable').getElementsByTagName('tr');
for(var j=0;j<allFields.length;j++){
emptyRows[i+1].innerHTML = "<td>" + allFields[j].value + "</td>" ;
}}
break;
case 'publish' :
var sortedPublishedDates= publishedDates.sort();
for(var i=0;i<publishedDates.length;i++){
var foundRecord = recordSearch(publishedDates[i]);
var allFields = foundRecord.getElementByTagName('tr').getElementsByClassName('td');
var emptyRows = document.getElementById('sortedTable').getElementsByTagName('tr');
for(var j=0;j<allFields.length;j++){
emptyRows[i+1].innerHTML = "<td>" + allFields[j].value + "</td>" ;
}}
break;
}
}
<!-- -------------------------------------------------------------------- -->
Put them together and Try. Let me know if it works.

Categories