Chrome Debugging tips

Dev tools are built into the Chrome browser. You can launch the browser and simply launch them with a short cut key (F12 on Windows or CMD_OPT_i on a Mac). Dev tools may launch either docked to a side in your browser or they can be free floating. This behavior can be toggled via the triple dot menu on the top right hand corner of dev tools, as shown in Figure 1.

Figure 1: Changing how dev tools appear

As you can see, dev tools are fairly involved. They’re organized into various tabs, such as Elements, Console, Sources, Network, Performance, and so much more.

Continue reading..

Front End Plugins

This is a list of various front-end plugins and visual components.

TreeView

https://jonmiles.github.io/bootstrap-treeview/

This plugin leverages the best of bootstrap framework and helps you display hierarchical tree structures using the JSON data set.

To read more, read this

Download from here

Bootstrap Material Select

Bootstrap Material Select is a form control that, after a click displays a collapsable list of multiple values which can be used in forms, menus or surveys.

For more info, read this

Bootstrap selectpicker class

Add the selectpicker class to your select elements to auto-initialize bootstrap-select.

<select class="selectpicker">
  <option>Mustard</option>
  <option>Ketchup</option>
  <option>Barbecue</option>
</select>

Via JavaScript

// To style only selects with the my-select class
$('.my-select').selectpicker();

or

// To style all selects
$('select').selectpicker();

If calling bootstrap-select via JavaScript, you will need to wrap your code in a .ready() block or place it at the bottom of the page (after the last instance of bootstrap-select).

Download from here

JavaScript quick sheet

Clearing all items from array;

list = [];
or
list.length = 0;

Concatenate two numbers;

let myId = "" + bookId + bookSerialId;

Create a div and attach click event in jQuery

//HTML
<input type=button value='Remove All' id='b1' />

//jQuery
 $(document).ready(function () {

   //any function after DOM is ready

   //Click event
   $("#b1").click(function () {

       console.log("what you wanna do?");
   });
});

Creating classes with private counter

class BookStore {
   static #lastKey = 0;   //this is private
   key;
   bookId = 0;
   bookTitle = "";
   rackId = 0;
   constructor(bookId, bookTitle, rackId) {
      this.key = ++BookStore.#lastKey;
      this.bookId = bookId;
      this.bookTitle = bookTitle;
      this.rackId = rackId;   //sort function
      }
}

//usage
let bookRecord = new BookStore(1, "Funny jokes", 1);
bookList = [];
bookList.push(bookRecord);

Add and Get DIV values;

<div id="myDiv"><p>Some Text</p></div>
var txt = $('#myDiv p').text();
alert(txt);

Check for undefined or null variable

if ( some_variable == null ){
  // some_variable is either null or undefined
}
So these two lines are equivalent:
if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}

Nowadays most browsers support the Nullish coalescing operator (??) and the Logical nullish assignment (??=), which allows a more concise way to assign a default value if a variable is null or undefined, for example:

if (a.speed == null) {
  // Set default if null or undefined
  a.speed = 42;
}
can be written as any of these forms

a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;

JSON.parse() does not allow trailing commas

// both will throw a SyntaxError
JSON.parse("[1, 2, 3, 4, ]");
JSON.parse('{"foo" : 1, }');

JSON.parse() does not allow single quotes

// will throw a SyntaxError
JSON.parse("{'foo': 1}");

Read JSON String

// Make sure, valid JSON is provided
const jsonData = @Json.Serialize(Model.JsonData);

Adding markup to existing HTM elements by finding a bootstrap class within another class e.g.

<div class="outer">
     <div class="inner"></div>
</div>

The easy to find solution is;
$container.find('.outer').find('.inner')

Single selector syntax is;
$('.outer > .inner')

For example;
$('.outer > .inner').append("<p>Shahzad</p>");
OR
let container = $('.outer > .inner');
container.append("<p>Shahzad</p>");

For more info Read here;

https://api.jquery.com/prepend/

Adding HTML markup to existing HTLM elements decorated with multiple class names. For example;

<div class="form-check form-check-inline inner">
</div>

jQuery code
$('.form-check.form-check-inline.inner').append("<p>Shahzad-.form-check.form-check-inline.inner</p>");

OR
let container = $('.form-check.form-check-inline.inner').append("<p>Shahzad-.form-check.form-check-inline.inner</p>");
container.append("<p>Shahzad - form-check-inline container object</p>");

Using backtick in JavaScript

This is a feature called template literals.

They were called “template strings” in prior editions of the ECMAScript 2015 specification.

Template literals are supported by Firefox 34, Chrome 41, and Edge 12 and above, but not by Internet Explorer.

Template literals can be used to represent multi-line strings and may use “interpolation” to insert variables:

var a = 123, str = `---
   a is: ${a}
---`;
console.log(str);

Output:

---
   a is: 123
---

What is more important, they can contain not just a variable name, but any JavaScript expression:

var a = 3, b = 3.1415;

console.log(`PI is nearly ${Math.max(a, b)}`);

Read more here

Here is an example of creating Checkbox using jQuery and Bootstrap

Using Prepend in jQuery

The jQuery Prepend method prepends the content inside of every matched element (selector) i.e. it insert the specific content as the first child of the selector.

jQuery Prepend jQuery Object

$("#prependDiv").prepend("To Tanolis, ","Are you enjoying, ", " coding?")

HTML output
<div id="prependDiv">To Tanolis, Are you enjoying, coding? Welcome</div>

jQuery Prepend HTML
<div id="prependDiv">
    Welcome
</div>
$("#myDiv").prepend("<p>To Tanolis. Are you enjoying coding?</p>")

HTML output
<div id="myDiv">
    <p>To Tanolis. Are you enjoying coding?</p>
    Welcome
</div>

Creating element without closing tag in jQuery

Tags are used to create elements in HTML.

jQuery allows you to use HTML syntax to create elements, but this is just an abstraction. jQuery does not keep a string of HTML in memory and allow you to modify it. It is dealing with whole elements.

If you want to work with a string of HTML, then you need to deal with a string and not jQuery.

It’s better to work with elements though. Create the div with $() and not append(). Add children to it. Append it to the parent element.

function createRow(divName) {
     var row = $("<div />");
     row.addClass("row");
     $("#"+ divName).append(div);
     return row;
}

How create elements for Bootstrap Card CSS class

Suppose we have this card;

<div class="card">
  <h4 class="card-header">jQuery Object</h4>
  <h5 class="card-header"><span id="selectedNode-title"></span></h5>
  <div class="card-body roles">
      <div class="form-check form-check-inline">
         <input class="form-check-input" type="checkbox" id="chk_405" value="405">
         <label class="form-check-label" for="chk_405">Project Manager</label>
      </div>
      <!--dynamic one are here-->
      <br />
      <a href="#" class="btn btn-primary">Go somewhere</a>
   </div>
</div>

This card has one open HTML element that wraps all other elements around.

<div class="card-body roles">

Inside above HTML, there is another open HTML element.

<div class="form-check form-check-inline">

We need to create this html fragment dynamically for each HTML control.

      <div class="form-check form-check-inline">
         <input class="form-check-input" type="checkbox" id="chk_405" value="405">
         <label class="form-check-label" for="chk_405">Project Manager</label>
      </div>

We can not use jQuery object to create this fragment because HTML object will put end tag to each start tag.

This is jQuery / JavaScript;

let container = $('.card-body.roles');

let openTag = $('<div>', { 'class': 'openTabExperiment' });
let input = $('<input />', { type: 'checkbox', id: 'chk_' + role.roleId, value: role.roleId, class: 'form-check-input' });
let label = $('<label />', { 'for': 'chk_' + role.roleId, text: role.roleName, class: 'form-check-label' });

//A single tag has bootstrap card elements. jQuery object doesn't allow to crate open tag element
. We are adopting HTML fragment path here.

let htmlFragment = '';

htmlFragment += '<div class="form-check form-check-inline">';
htmlFragment += input.get(0).outerHTML
htmlFragment += label.get(0).outerHTML;
htmlFragment += '</div><br />'
console.log(htmlFragment);
container.append(htmlFragment);

This will create required Bootstrap and Html elements.

Json object from Razor model in Javascript

Let’s begin with a model.

public class RoleModel
{ 
     public int RoleId { get; set; }
     public string RoleName { get; set; }
}

Add some data to the model;

List<RoleModel> roles = new List<RoleModel> {
     new RoleModel{
                     RoleId= 1,
                     RoleName = "Administrator"
                },
     new RoleModel
                {
                     RoleId = 2,
                     RoleName = "Manager"
                }
            };

Pass this to razor view;

@model List<RoleModel>

Declare Javascript Sections in your razor view;

<end of HTML here>
@section Scripts
{
    //go with jQuery ready function
    $(document).ready(function () {
       //get model data here
       var roles = @Html.Raw(Json.Serialize(Model.Roles));

       //iterate through model data

       $.each(roles, function(i, role){
            console.log(role.roleName);
      });
  }
}

This will output this data;

AspNetCore

AspNetCore uses Json.Serialize intead of Json.Encode

var json = @Html.Raw(Json.Serialize(@Model.Roles));

MVC 5/6

You can use Newtonsoft for this:

    @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model, 
Newtonsoft.Json.Formatting.Indented))

This gives you more control of the json formatting i.e. indenting as above, camelcasing etc.