x This domain is for sale. If you intrested, Please contact : webspeckle@gmail.com

Search and get the postion of an element in jquery

index() is used for search for a given element from among the matched elements.

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

If a selector string is passed as an argument, .index() returns an integer indicating the position of the first element within the jQuery object relative to the elements matched by the selector. If the element is not found, .index() will return -1.

Eg:
<ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
  <li id="baz">baz</li>
</ul>
var listItem = document.getElementById( "bar" );
console.log( "Index: " + $( "li" ).index( listItem ) );
We get back the zero-based position of the list item:

Index: 1

Sample code and demo is here

Demo

Load a JavaScript file dynamically

Load a JavaScript file dynamically using jQuery

jQuery.getScript()
Load a JavaScript file from the server using a GET HTTP request, then execute it.

Eg:
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
  console.log( data ); // Data returned
  console.log( textStatus ); // Success
  console.log( jqxhr.status ); // 200
  console.log( "Load was performed." );
});
By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested. You can override this feature by setting the cache property globally using $.ajaxSetup():

$.ajaxSetup({
  cache: true
});
Sample code and demo

Demo

How to send HTTP request in spring boot?

If you need to call remote REST services from your application, you can use Spring Framework’s RestTemplate class. Since RestTemplate instances often need to be customized before being used, Spring Boot does not provide any single auto-configured RestTemplate bean. It does, however, auto-configure a RestTemplateBuilder which can be used to create RestTemplate instances when needed. The auto-configured RestTemplateBuilder will ensure that sensible HttpMessageConverters are applied to RestTemplate instances.

RestTemplateBuilder includes a number of useful methods that can be used to quickly configure a RestTemplate. For example, to add BASIC auth support you can use builder.basicAuthorization("user", "password").build().


Eg:
HttpResponse httpResponse;
HttpRequest httpRequest = new HttpRequest();
HttpRequest.setName("webspeckle.com");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<HttpRequest> entity = new HttpEntity<>(httpRequest,headers);

RestTemplate restTemplate = new RestTemplate();

try
{
    ResponseEntity<HttpResponse> responseEntity = restTemplate.exchange("REST_URL", HttpMethod.POST, entity, HttpResponse.class);
    httpResponse = responseEntity.getBody();
    //Success
}
catch(HttpStatusCodeException ex)
{
    //Error in REST request
}

Http status code quick reference

Status codes in the 100x range (from 100-199) are informational, and describe the processing for the request.

Status codes in the 200x range (from 200-299) indicate the action requested by the client was received, understood, accepted and processed successfully

Status codes in the 300x range (from 300-399) indicate that the client must take additional action to complete the request, such as following a redirect

Status codes in the 400x range (from 400-499) is intended for cases in which the client seems to have erred and must correct the request before continuing. The aforementioned 404 is an example of this.

Status codes in the 500x range (from 500-599) is intended for cases where the server failed to fulfill an apparently valid request.

Change message converter to Gson in RestTemplate

Message converters are used to convert the Http request to an object representation and back.

RestTemplate restTemplate = new RestTemplate();
           
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
messageConverters.add(gsonHttpMessageConverter);
restTemplate.setMessageConverters(messageConverters);

Search a string in JavaScript

The indexOf() method returns the position of the first occurrence of a specified string value in a string.

stringObject.indexOf(searchvalue,fromindex) 
searchvalue Required. Specifies a string value to search for
fromindex Optional. Specifies where to start the search

Tips and Notes
Note: The indexOf() method is case sensitive!

Note: This method returns -1 if the string value to search for never occurs.

Example
In this example we will do different searches within a "Hello world!" string:
<script type="text/javascript">
var str="Hello world!";
document.write(str.indexOf("Hello") + "<br />");
document.write(str.indexOf("World") + "<br />");
document.write(str.indexOf("world"));
</script> 
The output of the code above will be:

0
-1
6

Final code and demo is here

Demo

Get year in JavaScript

The getYear() method returns the year, as a two-digit OR a four-digit number.

dateObject.getYear() 
Tips and Notes
Note: The value returned by getYear() is not always 4 numbers! For years between 1900 and 1999 the getYear() method returns only two digits. For years before 1900 and after 1999 it returns four digits!
This method is always used in conjunction with a Date object.

Important: The getYear() method should no longer be used. Use the getFullYear() method instead!!

Example
In this example we get the current year and print it:
<script type="text/javascript">
var d = new Date()
document.write(d.getYear())
</script> 
The output of the code above will be:

105

Example 2
Here we will extract the year out of the specific date:
<script type="text/javascript">
var born = new Date("July 21, 1983 01:15:00");
document.write("I was born in " + born.getYear());
</script> 

Convert JSON string to object in PHP

json_decode — Decodes a JSON string. Takes a JSON encoded string and converts it into a PHP variable.

Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

Eg:
<?php
$json = '
    {
        "color":"red",
        "font-size":"12px",
        "background-color":"#F5F5F5",
        "height":"40px",
        "width":"100%"
    }';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
Output:
object(stdClass)#196 (5) {
  ["color"]=>
  string(3) "red"
  ["font-size"]=>
  string(4) "12px"
  ["background-color"]=>
  string(7) "#F5F5F5"
  ["height"]=>
  string(4) "40px"
  ["width"]=>
  string(4) "100%"
}
array(5) {
  ["color"]=>
  string(3) "red"
  ["font-size"]=>
  string(4) "12px"
  ["background-color"]=>
  string(7) "#F5F5F5"
  ["height"]=>
  string(4) "40px"
  ["width"]=>
  string(4) "100%"
}

Add www to your domain using htaccess

To automatically add a www to your domain name when there isn't a subdomain, add this to the htaccess file in your document root:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]

Onclick event in JavaScript

The onclick event occurs when an object gets clicked.

Syntax
onclick="SomeJavaScriptCode" 
Parameter: SomeJavaScriptCode
Description: Required. Specifies a JavaScript to be executed when the event occurs.

Example
In this example the text in the first input field will be copied to the second input field when a button is clicked:

Demo

Encode a set of form elements as a string for submission

The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements.

.serialize( )
Eg:
<form>
  <div><input type="text" name="a" value="1" id="a" /></div>
  <div><input type="text" name="b" value="2" id="b" /></div>
  <div><input type="hidden" name="c" value="3" id="c" /></div>
  <div>
    <textarea name="d" rows="8" cols="40">4</textarea>
  </div>
  <div><select name="e">
    <option value="5" selected="selected">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
  </select></div>
  <div>
    <input type="checkbox" name="f" value="8" id="f" />
  </div>
  <div>
    <input type="submit" name="g" value="Submit" id="g" />
  </div>
</form>
The .serialize() method can act on a jQuery object that has selected individual form elements, such as <input>, <textarea>, and <select>. However, it is typically easier to select the <form> tag itself for serialization:

$('form').submit(function()
{
  alert($(this).serialize());
  return false;
});
This produces a standard-looking query string:

a=1&b=2&c=3&d=4&e=5
Warning: selecting both the form and its children will cause duplicates in the serialized string.

Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

Final code and demo is here

Demo

What is gulp.js?

gulp is a toolkit that helps you automate painful or time-consuming tasks in your development workflow. It is a task runner built on Node.js and npm, used for automation of time-consuming and repetitive tasks involved in web development like minification, concatenation, cache busting, unit testing, linting, optimization etc.

Getting Started


1) Install 'nodejs'
2) Create 'package.json'
3) Create 'gulpfile.js'
4) run 'gulp' command

Install 'nodejs'

After installing go to the project directory through 'Node.js command prompt' and check the version first
node --version
npm --version
Install the gulp command
npm install --global gulp-cli

Create a package.json

npm init
If you don't have a package.json, create one. If you need help, run an 'npm init' which will walk you through giving it a name, version, description, etc.
A sample file look like this
{
  "name": "PROJECT_NAME",
  "version": "PROJECT_VERSION",
  "description": "PROJECT_DESCRIPTION",
  "main": "",
  "dependencies": {
    "gulp": "^3.9.1"
  },
  "devDependencies": {
    "del": "^3.0.0",
    "gulp": "^3.9.1",
    "gulp-concat": "^2.6.1",
    "gulp-uglify": "^3.0.0",
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "AUTHOR",
  "license": "ISC"
}
Install gulp in your devDependencies
npm install --save-dev gulp

Create a gulpfile

In your project directory, create a file named gulpfile.js in your project root.
A sample file look like this
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var del = require('del');
var paths = {
  scripts: ['client/js/**/*.js']
};

gulp.task('clean', function() {
  return del(['build']);
});
gulp.task('scripts', ['clean'], function() {
  // Minify and copy all JavaScript (except vendor scripts)
  return gulp.src(paths.scripts)
      .pipe(uglify())
      .pipe(concat('all.min.js'))
    .pipe(gulp.dest('build/js'));
});

gulp.task('default', ['scripts']);

Run gulp

gulp
run 'gulp' command in 'Node.js command prompt'

After run gulp command all your 'js' files minimized and compressed to a single file 'all.min.js.' A folder 'build' will create in your project directory. It has another folder 'js'. This 'js' folder contains a single js file 'all.min.js'.

Free file and folder comparison tool for developers

Meld is a visual diff and merge tool targeted at developers. Meld helps you compare files, directories, and version controlled projects. It provides two- and three-way comparison of both files and directories.

Meld is packaged for most Linux/Unix distributions, including Fedora, Ubuntu, and Suse. Unless you want the absolutely latest version, you should install Meld through your package manager.

Features
Two- and three-way comparison of files and directories
File comparisons update as you type
Auto-merge mode and actions on change blocks help make merges easier
Visualisations make it easier to compare your files
Supports Git, Bazaar, Mercurial, Subversion, etc.

Visit: http://meldmerge.org/

Meld is licensed under the GPL v2, except as noted. 

Is Qt supports JSON?

YES. Qt provides support for dealing with JSON data. JSON is a format to encode object data derived from Javascript, but now widely used as a data exchange format on the internet. The JSON support in Qt provides an easy to use C++ API to parse, modify and save JSON data. It also contains support for saving this data in a binary format that is directly "mmap"-able and very fast to access.

JSON is a format to store structured data. It has 6 basic data types:
bool, double, string, array, object, null
The text representation of JSON encloses arrays in square brackets ([ ... ]) and objects in curly brackets ({ ... }). Entries in arrays and objects are separated by commas. The separator between keys and values in an object is a colon (:).

A simple JSON document encoding a person, his/her age, address and phone numbers could look like:
{
    "FirstName": "John",
    "LastName": "Doe",
    "Age": 43,
    "Address": {
        "Street": "Downing Street 10",
        "City": "London",
        "Country": "Great Britain"
    },
    "Phone numbers": [
        "+44 1234567",
        "+44 2345678"
    ]
}
JSON support in Qt consists of these classes:
QJsonArrayEncapsulates a JSON array
QJsonDocumentWay to read and write JSON documents
QJsonParseErrorUsed to report errors during JSON parsing
QJsonObjectEncapsulates a JSON object
QJsonObject::const_iteratorQJsonObject::const_iterator class provides an STL-style const iterator for QJsonObject
QJsonObject::iteratorQJsonObject::iterator class provides an STL-style non-const iterator for QJsonObject
QJsonValueEncapsulates a value in JSON

Which are the supported databases in qt?

Qt5 supports SQLite, MySQL, DB2, Borland InterBase, Oracle, ODBC, and PostgreSQL.

The table below lists the drivers included with Qt. Due to license incompatibilities with the GPL, not all of the plugins are provided with Open Source Versions of Qt.

Driver nameDBMS
QDB2IBM DB2 (version 7.1 and above)
QIBASEBorland InterBase
QMYSQLMySQL
QOCIOracle Call Interface Driver
QODBCOpen Database Connectivity (ODBC) - Microsoft SQL Server and other ODBC-compliant databases
QPSQLPostgreSQL (versions 7.3 and above)
QSQLITE2SQLite version 2
QSQLITESQLite version 3
QTDSSybase Adaptive Server
Note: obsolete from Qt 4.7

How to check if a value is not a number in JavaScript?

The isNaN() function is used to check if a value is not a number.

Syntax
isNaN(number) 
Parameter: number Required.
Description: The value to be tested

Example
In this example we use isNaN() to check some values:
<script type="text/javascript">
document.write(isNaN(123)+ "<br />");
document.write(isNaN(-1.23)+ "<br />");
document.write(isNaN(5-2)+ "<br />");
document.write(isNaN(0)+ "<br />");
document.write(isNaN("Hello")+ "<br />");
document.write(isNaN("2005/12/12")+ "<br />");
</script>
The output of the code above will be:
false
false
false
false
true
true

Final code and demo is here

Demo

How to evaluates a string in JavaScript?

The eval() function evaluates a string and executes it as if it was script code.

Syntax
eval(string) 

Parameter: string Required.
Description: The string to be evaluated

Example
In this example we use eval() on some strings and see what it returns:
<script type="text/javascript">
eval("x=10;y=20;document.write(x*y)");
document.write("<br />");
document.write(eval("2+2"))
document.write("<br />");
var x=10
document.write(eval(x+17))
document.write("<br />")
</script>
The output of the code above will be:
200
4
27

Final code and demo is here

Demo

Get today's date and time in JavaScript

The Date() method returns today's date and time.

Syntax: Date()

Example
In this example we will print today's date and time:
<script type="text/javascript">
document.write(Date())
</script>
The output of the code above will be:

Thu Jul 27 2017 23:23:42 GMT+0530 (India Standard Time)

Final code and demo is here

Demo

Convert Boolean to string in Java

By using Boolean.toString() this method to covert Boolean to string in Java. This method accepts the boolean argument and converts it into an equivalent String value.

boolean status = false;
String str = Boolean.toString(status);
System.out.println("String value of 'status' is: "+str);

Form validation using JavaScript

Parsley is a javascript form validation library. It helps you provide your users with feedback on their form submission before sending it to your server. It saves you bandwidth, server load and it saves time for your users.

Javascript form validation is not necessary, and if used, it does not replace strong backend server validation.

That's why Parsley is here: to let you define your general form validation, implement it on the backend side, and simply port it frontend-side, with maximum respect to user experience best practices.

Basic installation
Parsley relies on jQuery (>= 1.8), and it will need to be included before including Parsley.
 Then, you can either use parsley.js unminified file or parsley.min.js minified one. These files and extras are available here.

Finally, add data-parsley-validate to each <form> you want to be validated.

That would look pretty much like this:
<script src="jquery.js"></script>
<script src="parsley.min.js"></script>

<form id="form">
...
</form>

<script>
  $('#form').parsley();
</script>
Final code and demo is here

Demo

Get Unicode of the character at a specified position

The charCodeAt() method returns the Unicode of the character at a specified position.

stringObject.charCodeAt(index)
Parameter: index Required
Description: A number representing a position in the string

Note: The first character in the string is at position 0.

Example
In the string "Hello world!", we will return the Unicode of the character at position 1:
<script type="text/javascript">
var str="Hello world!"
document.write(str.charCodeAt(1))
</script>
The output of the code above will be:
101

Final code and demo is here

Demo

How to get the character at a specified position?

In JavaScript the charAt() method returns the character at a specified position.

stringObject.charAt(index)
Parameter: index
Description: Required. A number representing a position in the string

Note: The first character in the string is at position 0.

Example
In the string "Hello world!", we will return the character at position 1:
<script type="text/javascript">var str="Hello world!"
document.write(str.charAt(1))
</script>
The output of the code above will be:
e
Final code and demo is here

Demo

Get value of a number rounded upwards

The ceil() method returns the value of a number rounded UPWARDS to the nearest integer.

Math.ceil(x)
'x' is required and should be a number

In the following example we will use the ceil() method on different numbers:
<script type="text/javascript">document.write(Math.ceil(0.60) + "<br />")
document.write(Math.ceil(0.40) + "<br />")
document.write(Math.ceil(5) + "<br />")
document.write(Math.ceil(5.1) + "<br />")
document.write(Math.ceil(-5.1) + "<br />")
document.write(Math.ceil(-5.9))
</script>
The output of the code above will be:
1
1
5
6
-5
-5

Final code and demo is here

Demo

How to create a modal dialog in bootstrap?

Modal is basically a dialog box or popup window that is used to provide important information to the user or prompt user to take necessary actions before moving on. You can easily create very smart and flexible dialog boxes with the Bootstrap modal plugin.

Change the size of the modal by adding the .modal-sm class for small modals or  .modal-lg class for large modals.

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
  Open modal dialog
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Via data attributes

Activate a modal without writing JavaScript. Set data-toggle="modal" on a controller element, like a button, along with a data-target="#foo" or href="#foo" to target a specific modal to toggle.

<button type="button" data-toggle="modal" data-target="#myModal">Launch modal</button>

Via JavaScript

Call a modal with id myModal with a single line of JavaScript:
$('#myModal').modal(options)

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as i
Name Type Default Description
backdrop boolean or the string 'static' true Includes a modal-backdrop element. Alternatively, specify static for a backdrop which doesn't close the modal on click.
keyboard boolean true Closes the modal when escape key is pressed
show boolean true Shows the modal when initialized.
remote path false This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.
If a remote URL is provided, content will be loaded one time via jQuery's load method and injected into the .modal-content div. If you're using the data-api, you may alternatively use the href attribute to specify the remote source. An example of this is shown below:



<a data-toggle="modal" href="remote.html" data-target="#modal">Click me</a>
Final code and demo is here

Demo

How to add required indication(*) in bootstrap form?

You can easily add asterisk (*) to the required field in bootstrap form fields. Add the below CSS to your page.

CSS:
.form-group.required .control-label:after
{
      content:"*";
      color:red;
}
Then add an additional 'required' class to the 'form-group' class.
<form>
      <div class="form-group required">
        <label class="control-label">Username</label>
        <input type="text" name="userName"/>
      </div>
</form>
final code and demo is here

Demo

Get the current position of an element in jQuery?

Object .offset( )

Get the current coordinates of the first element in the set of matched elements, relative to the document.

The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.

.offset() returns an object containing the properties top and left.

Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.

Object.offset( Object coordinates )

Set the current coordinates of every element in the set of matched elements, relative to the document.

The .offset() setter method allows us to reposition an element. The element's position is specified relative to the document. If the element's position style property is currently static, it will be set to relative to allow for this repositioning.

Final code and demo is here

Demo

How to get the arccosine of a number in JavaScript?

The acos() method returns the arccosine of a number as a numeric value value between 0 and PI radians.

Math.acos(x)
Parameter is required and must be a numeric value in the range -1 to 1

Note: If the parameter x is outside the range -1 to 1, the browser will return NaN.
Note: -1 will return the value of PI

In this example we will get the arccosine of different numbers:
<script type="text/javascript">
document.write(Math.acos(0.64) + "<br />")
document.write(Math.acos(0) + "<br />")
document.write(Math.acos(-1) + "<br />")
document.write(Math.acos(1) + "<br />")
document.write(Math.acos(2))</script>
Sample code and demo is here

Demo

Get value of a number rounded downwards

The floor() method returns the value of a number rounded DOWNWARDS to the nearest integer in JavaScript.

Math.floor(x)
x is required and a number.

In this example we will use the floor() method on different numbers:
<script type="text/javascript">document.write(Math.floor(0.60) + "<br />")
document.write(Math.floor(0.40) + "<br />")
document.write(Math.floor(5) + "<br />")
document.write(Math.floor(5.1) + "<br />")
document.write(Math.floor(-5.1) + "<br />")
document.write(Math.floor(-5.9))
</script>
The output of the code above will be:
0
0
5
5
-6
-6

Final code and demo is here

Demo

How to get the absolute value of a number in JavaScript?

The abs() method returns the absolute value of a number.

Math.abs(x)
Parameter is required and must be a numeric value.

Example
<script>
document.write(Math.abs(7.25) + "<br />")
document.write(Math.abs(-7.25) + "<br />")
document.write(Math.abs(7.25-10))
</script>
Sample code and demo is here

Demo

How to create Pie chart in JavaScript?

Pie chart is a type of graph in which a circle is divided into sectors that each represent a proportion of the whole. Pie charts are very widely used in the business world and the mass media.

Pie charts are probably the most commonly used charts. They are divided into segments, the arc of each segment shows the proportional value of each piece of data. They are excellent at showing the relational proportions between data.

Here i am using chartjs library for creating pie chart. 

Example Usage

var myPieChart = new Chart(ctx,{
    type: 'pie',
    data: data,
    options: options
})
;

Dataset Properties

The pie chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of a the dataset's arc are generally set this way.

Name Type Description
label String The label for the dataset which appears in the legend and tooltips.
backgroundColor Color[] The fill color of the arcs in the dataset.
borderColor Color[] The border color of the arcs in the dataset.
borderWidth Number[] The border width of the arcs in the dataset.
hoverBackgroundColor Color[] The fill colour of the arcs when hovered.
hoverBorderColor Color[] The stroke colour of the arcs when hovered.
hoverBorderWidth Number[] The stroke width of the arcs when hovered.

Config Options 

These are the customisation options specific to Pie charts. These options are merged with the global chart configuration options, and form the options of the chart.

NameTypeDefaultDescription
cutoutPercentageNumber0 - for pieThe percentage of the chart that is cut out of the middle.
rotationNumber-0.5 * Math.PIStarting angle to draw arcs from.
circumferenceNumber2 * Math.PISweep to allow arcs to cover
animation.animateRotateBooleantrueIf true, the chart will animate in with a rotation animation. This property is in the options.animation object.
animation.animateScaleBooleanfalseIf true, will animate scaling the chart from the center outwards.

Data Structure 

For a pie chart, datasets need to contain an array of data points. The data points should be a number, Chart.js will total all of the numbers and calculate the relative proportion of each. You also need to specify an array of labels so that tooltips appear correctly

data = {
    datasets: [{
        data: [10, 20, 30]
    }],

    // These labels appear in the legend and in the tooltips when hovering different arcs
    labels: [
        'Red',
        'Yellow',
        'Blue'
    ]
};
You can download the latest version of Chart.js from the GitHub releases or use a Chart.js CDN.

The final code & demo is here

Demo

How to add slim progress bars in JavaScript?

Use 'NProgress.js' library for nanoscopic progress bar.

NProgress.start() — shows the progress bar
NProgress.set(0.4) — sets a percentage
NProgress.inc() — increments by a little
NProgress.done() — completes the progress

<script>
NProgress.start();
$(document).ready(function ()
{
    NProgress.done();
});
</script>
Final code and demo is here

Demo

How to encode a URL in JavaScript?

The encodeURI() function is used to encode a URI.
This function encodes special characters, except: , / ? : @ & = + $ #

Eg:
<script>
var URL = "https://www.webspeckle.com/p/online-html-editor.html?filename=How to encode a URL in JavaScript";
var EncodedURL = encodeURI(URL);
</script>
Final code and demo is here

Demo

How to decode a URL in JavaScript?

The decodeURI() function is used to decode a URI.

Eg:
<script>
var URL = "https://www.webspeckle.com/p/online-html-editor.html?filename=How%20to%20decode%20a%20URL%20in%20JavaScript";
var EncodedURL = decodeURI(URL);
</script>
Final code and demo is here

Demo

What are the removed elements in HTML5?

The following elements are not available in HTML5

Tag Name Description
<acronym> Defines an acronym
<applet> Defines an applet
<basefont> Defines an base font for the page
<big> Defines big text
<center> Defines centered text
<dir> Defines a directory list
<font> Defines text font, size, and color
<frame> Defines a frame
<frameset> Defines a set of frames
<isindex> Defines a single-line input field
<noframes> Defines a no frame section
<s> Defines strike through text
<strike> Defines strike through text
<tt> Defines teletype text
<u> Defines underlined text

What is a subdomain?

Subdomain is a domain that is a part of a main domain. For example, abc.example.com. Here 'abc' is the subdomain and 'example.com' is the main domain. You can also add multiple levels of subdomains. Subdomains are different from directories. For example, example.com/abc points to a directory within the example.com domain, not to a subdomain of example.com.

The whole domain name does not exceed a total length of 255 characters, but in practice most domain registries limit at 253 characters.

What is a Domain name?

A domain name is an identification string that defines a realm of administrative autonomy, authority or control within the Internet. Domain names are formed by the rules and procedures of the Domain Name System (DNS). Any name registered in the DNS is a domain name. Domain names are used in various networking contexts and application-specific naming and addressing purposes. In general, a domain name represents an Internet Protocol (IP) resource, such as a personal computer used to access the Internet, a server computer hosting a web site, or the web site itself or any other service communicated via the Internet.

A domain name may point to multiple IP addresses to provide server redundancy for the services offered, a feature that is used to manage the traffic of large, popular web sites.

The domain name is a component of a uniform resource locator (URL) used to access web sites, for example:

https://www.google.com

In the above url
Protocol is 'https'
Subdomain is 'www'
domain name is 'google.com'

Domain names are organized in subordinate levels (subdomains) of the DNS root domain, which is nameless. The first-level set of domain names are the top-level domains (TLDs), including the generic top-level domains (gTLDs), such as the prominent domains com, info, net, edu, and org, and the country code top-level domains (ccTLDs). Below these top-level domains in the DNS hierarchy are the second-level and third-level domain names that are typically open for reservation by end-users who wish to connect local area networks to the Internet, create other publicly accessible Internet resources or run web sites.

How to get suggestions while type into the field?

In jQuery UI the Autocomplete API provides suggestions while you type into the field. The data source is a simple JavaScript array, provided to the API using the source-option. Autocomplete enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

Any field that can receive input can be converted into an Autocomplete, namely, <input> elements, <textarea> elements, and elements with the contenteditable attribute.

When typing in the autocomplete field, the plugin starts searching for entries that match and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.

$( ".selector" ).autocomplete({
  source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]
});
Final code and demo is here

Demo

How to remove white space from the beginning and end of a string in JavaScript?

Method 1: using trim()
The trim() method returns the string stripped of white space from both ends. trim() does not affect the value of the string itself.

var str = "    hello, how are you?    ";
str.trim(); //hello, how are you?
Method 2: using regex
The expression '/^\s+|\s+$/g' removes white space from both sides of a string.

var str = "    hello, how are you?    ";
str.replace(/^\s+|\s+$/gm,''); //hello, how are you?
Method 3: using JQuery
The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these white space characters occur in the middle of the string, they are preserved.

$.trim("    hello, how are you?    "); //hello, how are you?
Final code and demo is here

Demo

How to create pagination in Bootstrap?

This jQuery plugin "twbsPagination()" simplifies the usage of Bootstrap Pagintion.

Plugin requires jQuery (required - 1.7.0 or higher).

You can use Bootstrap CSS styles and markup (or use your own).

More details available here

Add this lines in to your HTML code
<div class="well PageContent"></div>
<ul class="PaginationLinks pagination-sm"></ul>
Add this script in to your JavaScript section
$('.PaginationLinks').twbsPagination(
{
    totalPages: 20,
    visiblePages: 7,
    onPageClick: function (event, PageNo) {
        $('.PageContent').text('Page ' + PageNo);
    }
});
Final code and demo is here

Demo

How to display dialog for user to input in JavaScript?

The prompt() is used for displays a dialog for user to input some text.

If the user clicks "OK", the input value is returned. If the user clicks "cancel", null is returned. If the user clicks OK without entering any text, an empty string is returned.

Dialog boxes are modal windows; they prevent the user from accessing the rest of the program's interface until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box

var Name = prompt("Please enter your name");
if (Name !== null)
{
    if (Name !== "")
    {
        //If the user clicks OK with text
    }
    else
    {
        //If the user clicks OK without entering any text
    }
}
Final code and demo is here

Demo

How to load Google map in Qt application?

Create an html file 'GMap.html' for Google map like this

<!DOCTYPE html>
<html>
<body>

<h1>How to load Google map in Qt application?</h1>

<div id="GMap" style="width:600px;height:600px;"></div>

<script>
function LoadGMap()
{
var mapOptions = {
    center: new google.maps.LatLng(36.778259, -119.417931),
    zoom: 5
}
var map = new google.maps.Map(document.getElementById("GMap"), mapOptions);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=LoadGMap"></script>

</body>
</html>
You must save 'GMap.html' file in your application directory. Then load this file in your Qt application.

In Qt5.5 =<
Header: #include <QWebView>
QString HTMLFilepath =  "YOUR_APPLICATION_PATH+/GMap.html";
QWebView *HTMLPage = new QWebView(parent);
HTMLPage->load(QUrl(QUrl::fromLocalFile(HTMLFilepath));
HTMLPage->show();
In Qt5.6 >=
Header: #include <QWebEngineView>
QString HTMLFilepath =  "YOUR_APPLICATION_PATH+/GMap.html";
QWebEngineView *HTMLPage = new QWebEngineView(parent);
HTMLPage->load(QUrl(QUrl::fromLocalFile(HTMLFilepath));
HTMLPage->show();
'load(url)' loads the specified url and displays it.

How to download file when clicking on the link?

In HTML5 <a> tag has a new "download" attribute.

Eg:
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj3_cJrsWP23faPEmIDCKvVH97xSZGJqUwdIWPQhad_fqgsZNbFjpCxZn9Uy4fjfV9MxCTNMLfw9s9MpUOczG8KNkR5_2pXO-vU2PwJ2EtuG_zhHiqvIyAgxiWgkyM_TqvzaCNLzqx4OCN_/s1600/HeaderLogo.png" download>
In the above example the image will be downloaded when a user clicks on the hyperlink.

The 'download' attribute will work with .pdf, .txt, .html, etc. file extensions.

Final code and demo is here


Demo

How to detect ENTER key press in HTML textbox?

Suppose you have a search form in your web page. User type search keyword in the textbox(input tag) and press the ENTER key instead of click on the search button. How to detect ENTER key press HTML input tag?

Eg:
<input type="text" id="SearchKeyword"/>
<button type="button" onclick="Search()">Search</button>
<script>
//Using JQuery
$('#SearchKeyword').keyup(function(e)
{
    if(e.keyCode == 13)
    {
        $(this).trigger("enterKey");
    }
});

//Using JavaScript
document.getElementById("SearchKeyword").onkeypress = function(e)
{
    if (e.keyCode === 13)
    {
        alert("Enter key pressed");
        Search();
    }
};
</script>
Final code and demo is here

Demo

How can i show confirmation box before page reload?

In some cases before page refresh/reload we have to show confirmation message to the user. The page reload only if the user allow. In JavaScript we can use 'onbeforeunload ' function for this case.

I have checked the below code in latest Chrome & Firefox.

<script>
window.onbeforeunload = function(event)
{
    return confirm("Confirm refresh");
};
</script>
Final code and demo is here


Demo

How to store JavaScript object in HTML attribute?

HTML5 has a new attribute "data-*". The data-* attributes is used to store custom data to the page. By adding data-* attributes, even ordinary HTML elements can become rather complex and powerful program-objects.

Eg:
<div data-website-name="webspeckle.com"></div>
In the above example 'div' element has an attribute "data-website-name". This is a custom data attributes. The string "webspeckle.com" set to "data-website-name" attribute.

Set JSON string in 'data' attribute

<div data-website-name="webspeckle.com" data-website-data='{"name":"webspeckle.com","type":"blog"}'></div>
In the above example the JSON string '{"name":"webspeckle.com","type":"blog"}' set to the 'data-website-data' attribute.

Get the value of data attribute using JQuery
$("div").data("data-website-name") //webspeckle.com
$("div").data("data-website-data") //JSON Object
$("div").data("data-website-data").type //blog
Set value to data attribute using JQuery
<script>
var car =
{
color: "red",
        owner: "rahul"
}
$(document).ready(function()
{
      $("div").data("car",car)
});
</script>
Final code and demo is here

Demo

How to add keyboard shortcut in JavaScript and JQuery?

Here i explain how to add 'Ctrl+S' and 'Alt+S' keyboard shortcut to your webpage using JQuery and JavaScript.

Please follow the below steps

1) Catch the 'keydown' event
2) Check whether 'Ctrl' key is pressed or not
3) Check whether the 'S' key is pressed or not
4) Prevent the default behavior of 'Ctrl+S'.

//In JQuery
<script>
    $(document).bind('keydown', function (e)
    {
        if (e.ctrlKey && (e.which === 83)) //Ctrl+S
        {
            e.preventDefault();
            alert('Ctrl+S Pressed');
            return false;
        }
    });
</script>
1) Catch the 'keydown' event
2) Check whether 'Alt' key is pressed or not
3) Check whether the 'S' key is pressed or not
4) Prevent the default behavior of 'Alt+S'.

//In JavaScript
<script>
document.onkeydown=function(e)
{
    var e = e || window.event; // for IE to cover IEs window object
    if(e.altKey && e.which === 83)
    {
        alert('Alt+S Pressed');
        return false;
    }
};
</script>
Some control key combinations have been reserved for browser usage only and can no longer be intercepted by the client side JavaScript in the web page.
Eg: Ctrl+N, Ctrl+W, Ctrl+T etc...

Note: In the demo page, after executing the below html code please click on the output pane and press 'Ctrl+S' & 'Alt+S'

Final code and demo is here


Demo

How to check whether a database is exist in Qt?

Check whether a PostgreSQL database is exist or not in Qt.

If we try to create a PostgreSQL database through a Qt application, we have to check whether the given database is exist or not. Otherwise an error occurred during database creation.

I have checked the below method in Qt5 and it is working fine. Please replace 'MY_DB_NAME' by your database name.

QSqlQuery DatabaseQuery;
if(DatabaseQuery.prepare("SELECT datname FROM pg_catalog.pg_database WHERE lower(datname) =  lower('MY_DB_NAME')"))
{
     if(DatabaseQuery.exec())
     {
          if(DatabaseQuery.size() == 0)
          {
               //Database not exist
          }
          else
          {
               //Database exist
          }
     }
}

How to show a confirmation box in JavaScript?

In JavaScript 'confirm()' function is used for this purpose. This method displays a dialog box with a specified message, along with an OK and a Cancel button.

The confirm() method returns true if the user clicked "OK", and false otherwise.

The parameter type of this function is 'String'. This method does not accept HTML string as parameter. For 'line-breaks' please use '\n'.

var UserAction = confirm("Are you sure you want to delete?");
if (UserAction  == true)
{
    //User pressed on OK button
}
else
{
    //User pressed on CANCEL button
}
Final code and demo is here


Demo

Search and highlight using JavaScript?

Using a regex rule for search a word in JavaScript

new RegExp("Keyword",'gim')
And replace the keyword by '<span class=\"Highlight\">Keyword</span>'

Defined a 'Highlight' css class for highlight the keyword.

<style>
.Highlight
{
  background-color:#FF9;
  color:#555;
}
</style>
JQuery 'unwrap()' methord is used for unwrap the previously highlighted elements.

Final code and demo is here

Demo