JavaScript

From Torben's Wiki
Jump to navigationJump to search

Basics

HTML Form Elements

Function of button click

<button id="submit" onclick="myFunction()">Anmelden</button>

Function on enter

<input type="number" id="threshold" name="threshold" min="50" max="500" step="1" value="300">
var input_threshold = document.getElementById("threshold");
    input_threshold.addEventListener("keydown", function (e) {
      // Enter is pressed
      if (e.keyCode === 13) {
        event.preventDefault();
        myFunction();
      }
    }, false); 

Variables

Arrays

Loop over all elements

var rows = table.getRows();
for (var i = 0; i < rows.length; i++) {
    var row = rows[i];
    ...
}

Element in Array

if(myArray.indexOf(myItem) > -1) {...}

Async fetching via JQuery

in HTML

<script src="lib/jquery-3.5.0.min.js"></script>

in JS

// array of promises for async fetching
const promises = [];

// ref dictionary to be fetched: Country Code -> Country Name
var mapCountryNames = {};

// fetch countries-latest-all.json containing country reference data like code and continent
function fetch_mapRefCountryData(mapCountryNames) {
    const url =
        "https://entorb.net/COVID-19-coronavirus/data/int/countries-latest-all.json";
    return $.getJSON(url, function (data) {
        console.log("success: mapCountryNames");
    })
        .done(function (data) {
            console.log("done: mapCountryNames");
            $.each(data, function (key, val) {
                mapCountryNames[data[key].Code] = data[key].Country;
            });
        })
        .fail(function () {
            console.log("fail: mapCountryNames");
        });
}

// Start the async fetching 
promises.push(fetch_mapRefCountryData(mapCountryNames, mapContinentCountries));

// Wait for all async promises to be done (all data is fetched), then print message
Promise.all(promises).then(function () {
    console.log("All data fetched");
});


Date handling

// calculate date via offset
const daysOffset = 7;
const s_data_last_date = "2020-04-01"
const ts_last_date = Date.parse(s_data_last_date)
var minDate = new Date(ts_last_date);
minDate.setDate(minDate.getDate() + daysOffset);

Helper Functions

from [https://love2dev.com/blog/javascript-remove-from-array/

function arrayRemove(arr, value) {
  return arr.filter(function (ele) { return ele != value; });
}

from [1]

function removeAllOptionsFromSelect(select) {
  var i, L = select.options.length - 1;
  for (i = L; i >= 0; i--) {
    select.remove(i);
  }
}

// Formats value "Something_Is_HERE" to "Something is here" like sentence
// value: The value to format
// separator: the separator string between words
function formatValueToSentenceLike(value, separator) {
  const allLowerCaseValue = value.split(separator).join(" ").toLowerCase();
  return allLowerCaseValue[0].toUpperCase() + allLowerCaseValue.substr(1);
}
// modifies array of objects by removing if value == keys
function arrayRemoveValueTextPairByValue(arr, key) {
  for (let i = arr.length - 1; i >= 0; i--) {
    if (arr[i].value == key) { arr.splice(i, 1); }
  }
}

Internet Explorer Backward Compatibility

Error: Object doesn't support property or method 'includes'

variant 1:

replace:

if(myarray.includes(key)) {

by:

if(myarray.indexOf(key) > -1) {

variant 2: polyfile

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';

    if (search instanceof RegExp) {
      throw TypeError('first argument must not be a RegExp');
    } 
    if (start === undefined) { start = 0; }
    return this.indexOf(search, start) !== -1;
  };
}