Showing posts with label js. Show all posts
Showing posts with label js. Show all posts

Friday, 5 October 2018

Javascript - refresh parent window when closing child window

var win = window.open("URL", '_blank');
var timer = setInterval(function () {
if (win.closed) {
 clearInterval(timer);
window.location.reload();
// Refresh the parent page
 }
 }, 1000);
 }

Wednesday, 22 August 2018

JS cookie handling

<script type='text/javascript'>
function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return false;
}
function eraseCookie(name) { 
    document.cookie = name+'=; Max-Age=-99999999;'; 
}
setCookie('TEST','Goal',7);
alert(getCookie('TEST'));
eraseCookie('TEST');
alert(getCookie('TEST'));
</script>

Friday, 18 May 2018

Difference between two dates in Javascript with demo


Enter values in mm/dd/yy hh:mm:ss format
First date and time
Second date and time
Result
In (decimal) hours
In (decimal) minutes
In seconds

Code:
<script type='text/javascript'>
function p (i){
return Math.floor(i / 10) + "" + i % 10;
}
function trunc (i){
var j = Math.round(i * 100);
return Math.floor(j / 100) + (j % 100 > 0 ? "." + p(j % 100) : "");
}
function calculate (form){
var date1 = new Date(form.date1.value);
alert(form.date1.value+"\n\n"+date1)
var date2 = new Date(form.date2.value);
var sec = date2.getTime() - date1.getTime();
if (isNaN(sec)){
alert("Input data is incorrect!");
return;
}
if (sec < 0){
alert("The second date ocurred earlier than the first one!");
return;
}
var second = 1000, minute = 60 * second, hour = 60 * minute, day = 24 * hour;
form.result_h.value = trunc(sec / hour);
form.result_m.value = trunc(sec / minute);
form.result_s.value = trunc(sec / second);
var days = Math.floor(sec / day);
sec -= days * day;
var hours = Math.floor(sec / hour);
sec -= hours * hour;
var minutes = Math.floor(sec / minute);
sec -= minutes * minute;
var seconds = Math.floor(sec / second);
form.result.value = days + " day" + (days != 1 ? "s" : "") + ", " + hours + " hour" + (hours != 1 ? "s" : "") + ", " + minutes + " minute" + (minutes != 1 ? "s" : "") + ", " + seconds + " second" + (seconds != 1 ? "s" : "");
}
</script>
<form id="form">
<table cellpadding="3">
<tr>
<td colspan="2" align="center">Enter values in <font color="#800000">mm/dd/yy hh:mm:ss</font> format</td>
</tr>
<tr>
<td>First date and time</td>
<td><input type="text" name="date1" /></td>
</tr>
<tr>
<td>Second date and time</td>
<td><input type="text" name="date2" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" name="submit" value="Calculate" onclick="calculate(this.form)" /></td>
</tr>
<tr>
<td>Result</td>
<td colspan="2"><input type="text" name="result" readonly="readonly" size="40" /></td>
</tr>
<tr>
<td>In (decimal) hours</td>
<td colspan="2"><input type="text" name="result_h" readonly="readonly" /></td>
</tr>
<tr>
<td>In (decimal) minutes</td>
<td colspan="2"><input type="text" name="result_m" readonly="readonly" /></td>
</tr>
<tr>
<td>In seconds</td>
<td colspan="2"><input type="text" name="result_s" readonly="readonly" /></td>
</tr>
</table>

Wednesday, 5 November 2014

How to disable Ctrl+V (Paste) , Ctrl+X (Cut) and Ctrl+C (Copy) with jQuery?

<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
 $(document).ready(function(){
      $('#read').bind("cut copy paste",function(e) {
   e.preventDefault();
   alert(" 'Ctrl+c & Ctrl+x & Ctrl+v has been disabled' ")
      });
   });
});
</script>
<input type="text" id="read" />

How to disable right click in mouse event in jquery?

<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
 $(document).bind('contextmenu', function (e) {
  e.preventDefault();
  alert('Right Click is not allowed');
 });
});
</script>

Friday, 10 October 2014

Autocomplete JQuery script full source code example

<script src="http://www.jqueryautocomplete.com/js/jquery/jquery-1.7.1.min.js"></script>
<script src="http://www.jqueryautocomplete.com/js/jquery/jquery.ui.core.min.js"></script>
<script src="http://www.jqueryautocomplete.com/js/jquery/jquery.ui.widget.min.js"></script>
<script src="http://www.jqueryautocomplete.com/js/jquery/jquery.ui.position.min.js"></script>
<script src="http://www.jqueryautocomplete.com/js/jquery/jquery.ui.autocomplete.min.js"></script>
<link rel="stylesheet" href="http://www.jqueryautocomplete.com/js/jquery/smoothness/jquery-ui-1.8.16.custom.css"/>
<script>var data = [
  {"label" : "Aragorn"},
  {"label" : "Arwen"},
  {"label" : "Bilbo Baggins"},
  {"label" : "Boromir"},
  {"label" : "Frodo Baggins"},
  {"label" : "Gandalf"},
  {"label" : "Gimli"},
  {"label" : "Gollum"},
  {"label" : "Legolas"},
  {"label" : "Meriadoc Merry Brandybuck"},
  {"label" : "Peregrin Pippin Took"},
  {"label" : "Samwise Gamgee"}
  ];
</script>
<script>
$(function() {

 $( "#search" ).autocomplete(
 {
   source:data
 })
});
</script>

<input type="text" id="search" />

Thursday, 9 October 2014

Enter Floating Number only

Input field onkeyup check floating values only to allow
onkeyup="if (!isFinite(this.value)) this.value = this.value.replace(/(\s+)?.$/,'')"

Saturday, 4 October 2014

Wednesday, 1 October 2014

Easy to integrate Facebook login to your web application

<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<span id="status"></span>
<script type='text/javascript'>
function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    if (response.status === 'connected') {
      testAPI();
    } else if (response.status === 'not_authorized') {
      document.getElementById('status').innerHTML = 'Please log ' +'into this app.';
    } else {
      document.getElementById('status').innerHTML = 'Please log ' +'into Facebook.';
    }
}
function checkLoginState() {
    FB.getLoginStatus(function(response) {  statusChangeCallback(response); });
}

window.fbAsyncInit = function() {
    FB.init({
        appId      : "FB_APP_ID", 
        cookie     : true,  // enable cookies to allow the server to access // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.1' // use version 2.1
    });
    //FB.getLoginStatus(function(response) {  statusChangeCallback(response); });
};

(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
        console.log('Successful login for: ' + response.name);
        var name = response.name;
        var email = response.email;
        document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.email + '!';
    });
}
</script>

Friday, 26 September 2014

Push method for javascript array

JavaScript Array pop() Method
var actors = ["Rajini", "Kamal", "Ajith", "Vijay"];
actors.push("Surya");
The result of fruits will be:
Rajini,Kamal,Ajith,Vijay,Surya

To remove array Last index value Javascript

JavaScript Array pop() Method
var actors = ["Rajini", "Kamal", "Ajith", "Vijay"];
actors.pop();
The result of fruits will be:
Rajini,Kamal,Ajith

Thursday, 25 September 2014

How to add segment insertAfter specific id in jQuery?

<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("<p id=3>Hello world!</p>").insertAfter("#1"); }); }); </script> </head> <body> <button>Insert span element after each p element</button> <p id="1">This is a paragraph.</p> <p>This is another paragraph.</p> </body> </html>

Google Translator plugin for Browsers in Js

<script type="text/javascript">function googleTranslateElementInit() {
  var elem = new google.translate.TranslateElement({
    pageLanguage: "ca", 
    layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL,
    autoDisplay: false,
    floatPosition: 0
  });
  elem.onTurnOffLanguageClick = function() {
    var event = document.createEvent("Event");
    event.initEvent("translateExt_disable_lang", true, true);
    document.body.dispatchEvent(event);
  };
  var style = document.createElement("style");
  style.appendChild( document.createTextNode( ".global_header { top: 40px !important; }" ) );
  document.getElementsByTagName( "head" )[ 0 ].appendChild( style );
  elem.showBanner(false);
}</script>

Tuesday, 23 September 2014

How to convert string to number or integer in js?

var str = "123";
alert(str+"---"+typeof(str));
str = Number(str);
alert(str+"---"+typeof(str));

How to find variable type in js & jquery?

var str = "string";
alert(typeof(str)); //output: string

Input field enter integer only in jQuery

$(document).ready(function () {
    //called when key is pressed in textbox
    $("#quantity").keypress(function (e) {
        //if the letter is not digit then display error and don't type anything
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            //display error message
            $("#errmsg").html("Digits Only").show().fadeOut("slow");
            return false;
        }
    });
});

Number :
<input type="text" name="quantity" id="quantity" /> <span id="errmsg"></span>

Wednesday, 17 September 2014

How to get checked values in checkbox in dynamically by using jquery and javascript?

var chkArray = [];
$(".chk:checked").each(function() {
 chkArray.push($(this).val());
});
var selected;
selected = chkArray.join(',') + ",";
if(selected.length > 1){
 alert("You have selected " + selected); 
}else{
 alert("Please at least one of the checkbox"); 
}

Friday, 12 September 2014