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

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

How to change anchor element URL dynamically?

The HTML <a> element (or anchor element) creates a hyperlink to other web pages, files, locations within the same page, email addresses, or any other URL.

Change anchor element (<a>) href url dynamically by using jquery.

<script>
$(document).ready(function()
{
$("p").text("Anchor element url = "+$("a").attr("href"));
    $("button").click(function()
    {
        $("a").attr("href","http://www.webspeckle.com");
        $("p").text("Anchor element url = "+$("a").attr("href"));
    });
});
</script>
Final code and demo is here


Demo