Posts

Showing posts with the label JavaScript

Donate

Run JavaScript Snippets Using Google Chrome Developer Tools

Image
Good evening gents, Most of the time, we tend to write JavaScript snippets using IDE's or text editors and then run that using a webbrowser. However, you can compile and run JavaScript snippets using Google Chrome Developer tools directly. To utilize this feature, open a new Google Chrome browser and press F12 to show the developer tools. Click on the expand arrow beside FileSystem and choose Snippets . Paste your code inside the empty snippet window. To run your code, right click on the snippet and select Run. You should see the output in the Console window below.

Async Fetch Not Working When Retrieving Data From JSONPlaceholder API In JavaScript And Vue.JS

Image
Hello, I was trying to retrieve data from a Free Fake API website called JSON Placheholder using the code below which using asynchronous behavior. However, this does'nt return data after all. async getDataAsync(){ try { let response = await fetch( 'http://jsonplaceholder.typicode.com/todos' ); console.log(response.data); this .todos = response.data; } catch (error) { console.log(error); } After doing some research, I came up with a solution and replace the code above using JavaScript Promise as a means to retrieve data from the Fake API website in an asynchronous manner. await fetch( 'http://jsonplaceholder.typicode.com/todos' ) .then(response => response.json() ) .then(data => { this .todos = data; }) . catch (error => { return Promise.reject(error); }); } Cheers!

Bootstrap Table Cell Dynamic Background Width

Image
Good morning fellow programmers! I was recently tackling a task of which to set the Bootstrap Table cell by Wenzhixin background width dynamically based on a given value. Given that a the value to be accounted for is 25, then the table cell's background color should span to 25 pixels or percent only and not fill the entire table cell. To do that you need to create a custom function that will be used as the data-cell-style of a table column. The function below will return the css formatting of a table cell by setting the attributes color, background-image, background-repeat and background-size using the referenced value. function PercentBarCellStyle(value, row, index) { var classes = [ 'active' , 'success' , 'info' , 'warning' , 'danger' ]; var size = row.value.toString() + "% auto" ; return { css: { "color" : "transparent" , "background-image" : "url('https://add_you

Bootstrap Table Cell Background Conditional Formatting

Image
Lately I was working on a project that requires the Bootstrap Table cell by Wenzhixin to be filled with background color based from dynamic values similar to Power BI Conditional Formatting. The color density will change based from a value. Example is if the value is 0%, then the cell background is white. If value is 50% yellow. If 100% then dark orange. Other values will be calculated based on range percent. In order to achieve the task, you need to set the data-cell-style of the bootstrap table. <th data-field= "PercentValue" data-sortable= "true" data-searchable= "true" data-cell-style= "PercentValueCellStyle" >Percent %</th> The function to set the background color is defined below. function PercentValueCellStyle(value, row, index) { var classes = []; var percent = 0; var backColor = '' ; if (value == 0) { percent = 0; } else { percent = (value / 100).toFixed(1); } backColor = GetCo

How To Check If Two Arrays Are Equal Using JavaScript

Good afternoon fellow developers, I've been doing some checking if two arrays with same data types are equal in my client-side validation. A popular solution presented in stackoverflow is the function below. function CheckArrayEqualSort (arr1, arr2) { if (arr1.length !== arr2.length) { return false ; } var ar1 = arr1.concat().sort(); var ar2 = arr2.concat().sort(); for ( var i = 0; i < arr1.length; i++) { if (ar1[i] !== ar2[i]) { return false ; } } return true ; }; This does fulfill the requirement but performs sorting of elements first which tends to slow the comparison. So, I tend to modify the function to use indexOf() function which will check if an element in the first array object exists on the second array. Thus eliminate the sorting mechanism. function CheckArrayEqual (arr1, arr2) { if (arr1.length !== arr2.length) { return false ; } for ( var i = 0; i < arr1.length; i++) { if (arr2.indexOf(arr1[i]) < 0) {

How To The Get Index Of Selected Row Object In Bootstrap Table

Hello and good evening. Just sharing a snippet on how to get or retrieve the index of a selected row object given that you're working on the Bootstrap-Table developed by Wenzhixin. This assumes that you need to capture the index of the click-row.bs.table event. $( '#tblBillableSummary' ).on( 'click-row.bs.table' , function (e, row, $element) { var index = $element.data( 'index' ); }); Sample Fiddle: Get Index Of Selected Row Object In Bootstrap Table Cheers!

Bootstrap Table Format Numbers With Comma And Decimal Places In ASP.NET MVC

Image
Hello and Good Evening. Here's how to format numbers with comma and decimal places in Bootstrap Table columns by Wenzhixin using data-formatter tag. Simple set the data-formatter property of the tag. <table id= "tblBilling" data-toggle= "table" data-search= "true" data-advanced-search= "true" data-id-table= "billingTable" data-show-export= "true" data-toolbar= "#toolbar1" data-click-to-select= "true" data-height= "500" data-url= '@Url.Action("GetBillingInformation", "BillingDashboard")' data-cookie-id-table= "tblBillableID" > <thead> <tr style= "background-color: #FFFFFF;" > <td data-field= "CustomerID" data-sortable= "false" data-searchable= "false" data-visible= "false" >Customer ID</td> <td data-field= "

How To Change Open And Closed Folder Icons Of jsTree

To change the open and close folder icons, I found the answer here which is to set the 'open' and 'closed' properties of 'types' plugin. On the 'open_node' and 'close_node' events of the tree, set the data.nodes to 'open' and 'closed' respectively. See sample code below. function InitTreeEmployeesList() { $( '#jstree' ).jstree({ 'core' : { 'multiple' : false , 'themes' : { 'dots' : true , 'icons' : true } }, 'types' : { 'default' : { 'icon' : '../Content/Employee/Images/emp_default.png' }, 'open' : { 'icon' : '../Content/Employee/Images/employee_active.png' }, 'closed' : { 'icon' : '../Content/Employee/Images/emp_default.png' } },

Bootstrap Table Uncheck The Checkboxes On Page Load

Good evening all! When working with checkboxes in Bootstrap Table created by Wenzhixin, you may have notice that on page load the checkboxes are checked by default. If you want to uncheck these checkboxes on page load of your ASP.NET MVC page, call the checkInvert method of the bootstrap table on document ready of the page such as the code below: $(document).ready( function () { UncheckShoppingCartTable(); }); function UncheckShoppingCartTable() { $( '#tblShoppingCart' ).bootstrapTable( 'checkInvert' ); }

Parse And Replace Element Attribute Value Of Script Template Using jQuery

Good afternoon fellow programmers! I recently have a task to load a Script template that contains HTML markup to a page dynamically. But before loading the template, I need to change the attribute values of certain elements such as id and name. However, reading the template object made it difficult for me to convert it to an HTML object so I can traverse and manipulate the DOM. After doing research and some experiments, I found the solution presented below on how to read the value of a Script template and be able to use jQuery methods to traverse and update the DOM elements. Sample Script Template To Load In A Page <script type= "text/html" id= "templateGroup" > <div name= 'divChildSkill_' class= "col-md-12" id= "divChildSkill_" > <div class= "col-md-12" > <div class= "col-md-6" > <div class= "col-md-4" > <label id= "anchorLabel" >&l

Bootstrap Table Footer Data Footer Formatter Not Computing Correctly On Multiple Columns

Image
Good Afternoon! I recently faced a minor bug in Bootstrap Table by Wenzhixin using a single data-footer-formatter for four columns. I expected that this will compute the column values but the expected result shows that all columns total are zero. Bootstrap Table <table id= "tblBillingReport" class= "TableBorderCollapse table-striped " data-toggle= "table" data-search= "true" data-show-columns= "false" data-advanced-search= "false" data-id-table= "advancedTable" data-show-export= "true" data-toolbar= "#toolbar" data-click-to- select = "true" data-unique-id= "objectID" data-cookie= "true" data-show-footer= "true" data-height= "700" data-cookie-id-table= "tblBillingReportID" > <thead> <tr style= "background-color: #FFFFFF;" > <th dat

Bootstrap Table Add Table Footer For Total Amount

Image
To add a footer row to the Bootstrap Table by Wenzhixin, set the data-show-footer attribute of that table to true. <table id= "tblInvoiceReport" data-show-footer= "true" > Next is to set the data-footer-formatter of the Amount column using a JavaScript function. <th data-field= "Amount" data-searchable= "true" data-class= "tdDetails" data-footer-formatter= "TotalFormatter" >Amount</th> And here's the JavaScript function to compute the total amount. function TotalFormatter (items) { var totalPrice = 0; items.forEach( function (item) { totalPrice = parseFloat(totalPrice) + parseFloat(item.Amount.replace( '$' , '' ).replace( ',' , '' )); }); return '$' + parseFloat(totalPrice).toLocaleString( undefined , { minimumFractionDigits: 2, maximumFractionDigits: 2 }); }; Output

Bootstrap Table Get Or Retrieve All Table Data On CheckAll Event

Good evening fellow developers! Here's are solutions on how to obtain the Bootstrap-Table by Wenzhixin data if the check all event is fired. The first one loops through the table rows and then looks for the element in the row that holds the data either in the element attribute or innerText and retrieves it using jQuery methods. $( '#AttachmentsTable' ).on( 'check-all.bs.table' , function (e, rows) { var allrows = $( "#AttachmentsTable tr" ); downloadAttachmentsArray.length = 0 ; downloadAttachmentsArray = []; $.each(allrows, function (i, item) { if (i > 0 ) { var aElem = $(item).find( 'a' ).attr( 'file' ); downloadAttachmentsArray.push({ Filename : aElem }); } }); }); The better solution uses the built-in getData method of the bootstrap table which returns an array. And then you may then loop through that array to get the data. $( '#AttachmentsTable' ).o

How To Sort Dates With Invalid Values In JavaScript

Given the sorting function below to sort dates, this doesn't add checking for invalid date values. In return, the sorting doesn't do any effect on the data provided. var DateSortWithValidation = function (a, b) { var dateA = new Date(a); var dateB = new Date(b); if (dateA < dateB) return -1; if (dateA > dateB) return 1; return 0; }; So I made a little modification to the function using isNan() for date validation which sorts the dates properly. var DateSortWithValidation = function (a, b) { var dateA = new Date(a); var dateB = new Date(b); if (isNaN(dateA)) { return 1; } else if (isNaN(dateB)) { return -1 } else { if (dateA < dateB) return -1; else if (dateA > dateB) return 1; else return 0; } }; Usage of the function. $(document).ready( function () { var dates = [ new Date( '08/25/2018' ), new Date( 'test' ), new Date( '09/15/2018' ), new Date( &#

Cannot read property 'DateSorter' of undefined in Bootstrap Table

Good evening gents! Doing some refactoring to one of my projects using the JavaScript prototype pattern, I encountered issues while calling the functions in prototype through the Bootstrap Table by Wenzhixin specifically in the data-sorter property. In document ready, I created an object of an EmployeeModel class that contains the function. $(document).ready( function () { EmployeeObj = new EmployeeModel(); }); And in the data-sorter property, I called the custom function to sort dates. <th data-field= "signout_time" data-sortable= "true" data-searchable= "true" data-sorter= "EmployeeObj.DateSorter" > @Html.DisplayNameFor(model => model.EmployeeList[0].SignOutTime) </th> Doing so, throws an exception "Cannot read property 'DateSorter' of undefined". After further investigation, the table has set values for data-sort-name and data-sort-order properties. <table id= "" data-sort-name=

Custom JavaScript Date Sorter Function For Bootstrap Table in ASP.NET MVC

Image
While working on a project that implements Bootstrap Table by Wenzhixin, one column returns a date value with the format of MMM-YYYY and this column is sortable. A solution I've come up is to use the flexibility of Moment.js. Here's to date sorter function for the column. function DateSorter(a, b) { var dateA = new Date(moment(a).format( 'MMM-YYYY' )); var dateB = new Date(moment(b).format( 'MMM-YYYY' )); if (dateA < dateB) return -1; if (dateA > dateB) return 1; return -0; } Then set the data-sorter property of the table column with the function name. <th data-field= "BillingMonth" data-sortable= "true" data-sorter= "DateSorter" >Billing Month</th> Output Sample Fiddle: Custom JavaScript Date Sorter Function For Bootstrap Table Using Moment.JS

Bootstrap Table JavaScript Data-Sorter For Currency Column

Image
If your Bootstrap Table by Wenzhixin has a string currency column with a dollar sign and you want to sort the amount which disregards the currency symbol, a solution would be to remove the currency symbol and comma using Regex in JavaScript. function AmountSorter(a, b) { var billA = Number (a.replace( /(^\$|,)/g , '' )); var billB = Number (b.replace( /(^\$|,)/g , '' )); if (billA < billB) return - 1 ; if (billA > billB) return 1 ; return - 0 ; } And in your Bootstrap Table column, set the data-sorter property with the name of your currency sorter function. <th data-field= "RegistrationFee" data-sortable= "true" data-sorter= "AmountSorter" > Registration Fee </th> Output Sample Fiddle: Bootstrap Table JavaScript Data-Sorter For Currency Column

ASP.NET Web Forms GridView With Running Total Per Group Using JavaScript

Image
Basing from the post DataTable With Running Total Per Group which applies running total to a DataTable object, we can also achieve the same functionality through the front-end side by changing the structure of the GridView control given that this is an ASP.NET WebForm application. The snippet to set the control's data source is simple such as below: dt.Columns.AddRange( new DataColumn[ 5 ] { new DataColumn( "SrNo" , typeof ( int )), new DataColumn ( "PartyName" , typeof ( string )), new DataColumn ( "ItemName" , typeof ( string )), new DataColumn ( "ChqAmt" , typeof ( int )), new DataColumn ( "PartyCode" , typeof ( string ))}); dt.Rows.Add( 1 , "ABC Water Supply" , "Construction Service" , 400 , "ABC" ); dt.Rows.Add( 2 , "ABC Pump Services" , "Type 24 Engine Pump" , 150 , "ABC" ); dt.Rows.Add( 3 , "ABC Water Supply" , "12 Ft Wa

Formatting Numbers Using toLocaleString() In JavaScript

I've been using a JavaScript 3rd party library to format numbers with comma and decimal place(s). The JavaScript library called NumberFormatter was introduced to me by my developer with exceptional skills in front-end programming. Due to simplicity sake, I'm exploring options if this can be achieved using an existing JavaScript function instead of using the existing 3rd party app. After doing some research, I found an answer here: How to use toLocaleString() and tofixed(2) in javascript which is to use toLocaleString() by setting the options minimumFractionDigits and maximumFractionDigits to 2. Number .prototype.toLocaleFixed = function (n) { return this .toLocaleString( undefined , { minimumFractionDigits : n, maximumFractionDigits : n }); }; Sample usage: var result = parseFloat (amount).toLocaleFixed( 2 )

Sorting Of <li> Elements Using jQuery sort() Method Not Working (Refresh Page Only) In ASP.NET

Given the simple sorting code below which changes the order of <li> elements to ascending order and assuming that the text content of each li elements are numbers. $( function () { $( '#sortList' ).click( function (e) { // Select all the li items var numbersList = $( '#numbersList li' ); numbersList.sort( function (a, b) { return parseInt ($(a).text(), 10 ) > parseInt ($(a).text(), 10 ); }).appendTo(numbersList.parent()); }); }); The code should work only to find out that the page will only refresh after the button click. And then the re-arranging of the elements are discarded. The simple fix to this issue is to add the preventDefault() to prevent the button's default behavior that is to post back. $( function () { $( '#sortList' ).click( function (e) { e.preventDefault(); var numbersList = $( '#numbersList li' ); numbersList.sort( function (a, b) { var temp1 = parseInt($

Donate