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.

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect