Thursday, 31 May 2012

JS & jQuery

OOP:--

1.  We can define two type of member in javascript: 
       a) instance member
      b)  class member
Instance Member:- It's only access by object or reference of class.
example: -

JSD = function() {
  var    name = null;
  this.setName = function(name) { this.name = name;},
  this.getName = function() {return this.name;}
}
For access the get/set method, need to create object for it.
 var _jsd = new JSD();
_jsd.set("Jagdeep Singh");
document.write(_jsd.getName());

Static Member:-- It can be access by instance and class name.
example:-
JSD.age = null;
 JSD.setAge = function(age){JSD.age=age;}
JSD.getAge = function(){return JSD.age;}
document.write(JSD.getAge());

 Example for creating class functions:--
window.DateTimeOperation = function() {
    var currentDate = new Date();
    this.getCurrentDateObj = function () {
        return this.currentDate;
    },
    this.getCurrentDate = function () {
        var _date = new Date();
        return ((_date.getMonth() + 1) + "/" + _date.getDate() + "/" + _date.getFullYear());
    },
    this.getDaysDiffFromNow = function (fromDate) {
        var now1 = new Date();
        var from1 = new Date(fromDate);
        return (parseInt((from1.getTime() - now1.getTime()) / (1 * 24 * 3600 * 1000)));
    },
    this.getBackDateFromNow = function (backDays) {
        var now2 = new Date();
        now2.setDate(now2.getDate() - backDays);
        return ((now2.getMonth() + 1) + "/" + now2.getDate() + "/" + now2.getFullYear());
    },
    this.getNextDateByDays = function (_days) {
        var _date = new Date();
        _date.setDate(_date.getDate() + _days)
        return _date;
    },
    this.convertDate = function (timestamp) {
        dd = new Date(timestamp);
        return monthNames[dd.getMonth()] + " " + dd.getDate() + "th " + dd.getHours() + ":" + dd.getMinutes();
    },
    this.getRangeDaysValue = function () {
        return ("days:" + getDaysBetweenDates(jQuery("#fromDateTime").val(), jQuery("#toDateTime").val()))
    },
    this.getDaysBetweenDates = function (fromDate, toDate) {
        var now = new Date(toDate);
        var from = new Date(fromDate);
        return Math.abs((parseInt((from.getTime() - now.getTime()) / (1 * 24 * 3600 * 1000))));
    },
    this.getRangeDaysValue = function () {
        var dateRange = jQuery("select#dateRange option:selected").val();
        if (dateRange == "range") {
            dateRange = ("days:" + getDaysBetweenDates(jQuery("#fromDateTime").val(), jQuery("#toDateTime").val()));
        }
        return dateRange;
    },
    this.toString = function () {
        return "EvaniosDateTimeOperation:- " + getCurrentDate();
    }
}


Date operations:--
                    function getDaysDiffFromNow(fromDate) {
                        var now = new Date();
                        var from = new Date(fromDate);
                        return (parseInt((from.getTime() - now.getTime()) / (1 * 24*3600*1000)));                       
                    }
                    function getBackDateFromNow(backDays) {
                        var now = new Date();
                        now.setDate(now.getDays()-backDays);
                        return ((now.getMonth()+1)+"/"+now.getDate()+"/"+now.getFullYear());
                    }
                    function getCurrentDate(){
                        var _date = new Date();
                        return (_date.getMonth()+"/"+_date.getDay()+"/"+_date.getFullYear());
                    }
                    function getNextDateByDays(_days){
                      var _date = new Date();
                      _date.setDate(_date.getDate()+_days)
                      return _date;
                    }

#> String.prototype.unescapeHtml = function () {
var temp = document.createElement("div");
temp.innerHTML = this;
var result = temp.childNodes[0].nodeValue;
temp.removeChild(temp.firstChild);
return result;
    }

#> function userAgent() {
var agent = navigator.userAgent.toLowerCase();
var flagForPs3 = false;
if(agent.indexOf('playstation 3') != -1) {
flagForPs3 = true;
}
return flagForPs3;
}
#> String.prototype.replaceAll = function(_replace,_replaceWith) {
var text = this.toString().split(_replace);
var tmpText = this.toString();
for(var i=0;i<text.length;i++) {
tmpText = tmpText.replace(_replace,_replaceWith);
}
return tmpText;

}

String.prototype.replaceAll = function(rep, repwith) {
  var _v = new String(this.valueOf()); var _arr = _v.split(rep);var _ns = "";
  for(var i = 0;i<_arr.length;i++){
    _ns += _arr[i]+ ((i<(_arr.length-1))?repwith:"");
  }
  return _ns;
}
OR
http://api.jquery.com/replaceAll/
================= XML PARSING ====================
1. function parseXMLString(txt) {
var xmlDoc = null;
if (window.DOMParser) {
              parser=new DOMParser();
  xmlDoc=parser.parseFromString(txt,"text/xml");
} else {
 xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
 xmlDoc.loadXML(txt);
}
return xmlDoc;
}
2.  function parseXMLURL(_url) {
var xhttp = null;
if(window.XMLHttpRequest)  {
 xhttp = new XMLHttpRequest();
} else  { // IE 5/6
               xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",_url,false);
xhttp.send();
xmlDoc=xhttp.responseXML;
  }
3. $.xmlParser(text);
4. $.jsonParser(jsonobjectAsString);

PRODUCT.XML
------------------

<allProduct>
<product id="home">
<List>
<Title>Testing</Title>
<Image>images/test.png</Image>
</List>
</product>
</allProduct>




$(data).find('product').each(function(){
dataId=$(this).attr("id");
$(this).find('List').each(function(i){
if(bodyId==dataId){
var Title = $(this).find("Title").text();
var Image = $(this).find("Image").text();
});
});

JSON PARSING
-------------------
[{
     "test" : [
                  {"testName" : "test1", "sDate" : "8/2/2012"},
                  {"testName" : "test2", "sDate" : "8/2/2012"}
       ],
      "users" : [
                  {"userName" : "user1", "sDate" : "8/2/2012"},
                  {"userName" : "user2", "sDate" : "8/2/2012"}
       ],
}]

$.each(data, function(key, item) {

          $.each(item,function(key,value){
alert(key +" :: "+ value);
           })

testJSON= item.testes;
userJSON = item.users;
});


=================END XML PARSING ====================
COOKIE FUNCTIONS:-

function getCookieValue(paramName){  
    var params = psnInfo.split(",");
    for (i=0; i<params.length;i++) {    
    param_name = params[i].substring(0,params[i].indexOf('=')); 
    if(param_name==paramName)
     return params[i].substring(params[i].indexOf('=')+1);
    } 
   }  
function createCookie(name,value,days) {
 
    var expires="";
    if(readCookie(name)){ return; }
    else{
    
    
        var date = new Date();
        date.setTime(date.getTime()+(7*24*60*60*1000));
        expires = "; expires="+date.toGMTString();        
        var domainName="localhost.com";
        var domainIs = "";
        document.cookie = name+"="+value+expires+"; path=/;"+domainIs;       
    }
}
ANOTHER EXAMPLE OF COOKIE:-
function getUserInfoFromCookie() {
    return getCookie('user_info');
}
           

function setUserCookie(userType) {            

   setCookie('user_info',userType,-1);
}
function setCookie(c_name,value,exdays) {
 
    var expires="";
    var date = new Date();
    date.setTime(date.getTime()+(7*24*60*60*1000));
    expires = "; expires="+exdays;//date.toGMTString();        
    var domainName="localhost.com";
    var domainIs = window.location.host;
    document.cookie = c_name+"="+value+expires+"; path=/;"+domainIs;       
   // alert("set: "+value+"::"+document.cookie);
}
function getCookie(c_name) {
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++) {
 alert(ARRcookies[i]);
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }

=======================VALIDATION======================

function validate() {
  var frmRef = document.forms['YOUR_FORM_NAME'];
  var eLength = frmRef.elements.length;
  var resp = true;
  //alert(eLength);
  var fieldName = "";
  var flag = true;
  for(var i = 0;i <eLength; i++) { 
  //alert(frmRef.elements[i].name);
   //alert();
   if (!$("input[name='"+frmRef.elements[i].name+"']:checked").val()) {
    alert('Please select all fields!!!');
    resp = false;
    break;
   }   
  }
  return resp;
 }

====================EMAIL-VALIDATION=================
function validateForm() {
 var lbpFrm = document.
 var email = $("#email").val();
 var urID= $("#urID").val();
 
 if(psnID == "") {
  alert("Please Enter ID!");
  return false;
 } else if(urID.length>16) {
  alert("Maximum character in urID is 16.");
  return false;
 }
 if (email == "") {
        alert("Please Enter Email Address");
        document.getElementById('email').focus();
        return false;
    }
    if (checkemail(email)==false) {
  alert("Please enter a valid email address.");
        document.getElementById('email').focus();
        return false;
    }
 return true; 
}
function checkemail(idobject){
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(idobject) == false) 
   {
   return false;
   }
}
============================= Number ==============================
function validateNumber(e) {

  var evtobj=window.event? event : e ;
  var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode;
  return (unicode>=48 && unicode<=57)?true:false;
} 
============================= IMAGE ================================
You can programmatically get the image and check the dimensions using Javascript...
var img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
================ HISTORY ================

<script>history.go(-1);</script>
=============CUSTOM-POPUP (ALERT BOX)===============
  • jAlert(message, [title, callback])
  • jConfirm(message, [title, callback])
  • jPrompt(message, [value, title, callback])
  • alert(message);
  • confirm(message); return true/false, true means ok, false means cancel
EXAMPLE:-
var ALERT_TITLE = "YOUR_TITLE";

var ALERT_BUTTON_TEXT = "Ok";
if(document.getElementById){

window.alert = function(txt1){
createCustomAlert(txt1);
 
}

} 
function createCustomAlert(txt1){

d = document;
if(d.getElementById("DIV_ID")) return;
var mObj = document.getElementsByTagName("body")[0].appendChild(document.createElement("div")); 
mObj.id = "DIV_ID";   
mObj.style.height = document.documentElement.scrollHeight + "px";
alertObj = mObj.appendChild(document.createElement("div"));
alertObj.id = "alertBox";

if(d.all && !window.opera) alertObj;
alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px"; 

alertObj.style.visiblity="visible";

h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode(ALERT_TITLE));
msg1 = alertObj.appendChild(d.createElement("p"));

msg1.innerHTML = txt1;
btn = alertObj.appendChild(d.createElement("a"));
btn.id = "closeBtn";
btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT) );
btn.href = "javascript:void(0);";
btn.focus();

btn.onclick = function(){ removeCustomAlert(); }
alertObj.style.display = "block";
btn1 = alertObj.appendChild(d.createElement("a"));
btn1.id = "closeBtn1";
btn1.appendChild(d.createTextNode(ALERT_BUTTON_TEXT) );
btn1.href = "javascript:void(0);";
btn1.focus();
btn1.onclick = function() { removeCustomAlert(); }
}});
function removeCustomAlert() {
 /* YOUR CODE */
}
http://projectshadowlight.org/jquery-easy-confirm-dialog/
http://api.jquery.com/category/events/
http://docs.sencha.com/ext-js/4-0/#
http://www.sencha.com/apps/
http://jqueryui.com/demos/dialog/
http://www.techflaps.com/2012/02/jquery-or-javascript-dialog-boxes/
http://labs.abeautifulsite.net/archived/jquery-alerts/demo/
http://www.quackit.com/javascript/popup_windows.cfm
http://www.quirksmode.org/js/events_properties.html
http://www.fokistudios.com/superfun/
http://www.quirksmode.org/js/events_properties.html
/*================== REMOVE -SPACE =================*/

var t = "JAGDEEP SINGH DHIMAN";
var re = new RegExp("[/\s(?! )/gi]", "g");
t = (t.replace(re,"-"))
alert(t);
In this example, I am replacing the space with '-'.

Remove Special Characters: like and trademark symbol
"JSD®".replace(/[^a-z0-9\s]/gi, '-').replace(/[_\s]/g, '-');

INTERNATIONAL PHONE REGX:-

var avidno = '1234567890';
function validate () {
    var regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;

   if (regex.test(avidno)) {
        alert('bingo');
        var altrstr = avidno.replace(regex, ' <span>$2</span>');
        alert(altrstr);
        // Valid international phone number
    } else {
        alert('uupss');
        // Invalid international phone number
    }
}

validate();

window.removeSpecialChars = function(str) {
      return  str.replace(/[^a-zA-Z 0-9]+/g,"");
}
window.removeSpecialCharsWithSpace = function (str) {
str = str.replace(/[^a-zA-Z 0-9]+/g,”).replace(/[_\s]/g,"");
}


String.prototype.removeHTMLTagAndReplaceSpecialSymbol = function(rplWith) {
//alert(this.toString().replace(/<[^>]+>/ig,""));
//var regex =   /*/(<([a-zA-Z>]+)>)/ig;*/ /*/<.*?>/g;*/ /*/([<a-zA-Z 0-9>])/ig;*/
if(!rplWith){
rplWith = " ";
}
return this.toString().replace(/<[^>]+>/ig,"").replace(/[^a-z0-9\s]/gi, rplWith);//.replace(/<\/?[^>]+(>|$)/g, "");//.replace(regex,"");;//.replace(/[_\s]/g, '-')
}

========== LOAD JS & CSS DYNAMICALY ==================
For it you can use the document.createElement("script");
Example 1:-
function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}
Example 2:-

function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file
References:-

http://www.nczonline.net/blog/2009/07/28/the-best-way-to-load-external-javascript/

http://www.ejeliot.com/blog/109

Sometimes it makes sense to dynamically load JavaScript library code only at the point at which it's required. If functionality which uses that library is used rarely then it makes little sense incur the overhead of an additional HTTP request or data transfer on page load.
We can dynamically load any JavaScript and add it to the document with the following function.

Making a dynamic request

  1. function loadScript(sScriptSrc) {
  2. var oHead = document.getElementById('head')[0];
  3. var oScript = document.createElement('script');
  4. oScript.type = 'text/javascript';
  5. oScript.src = sScriptSrc;
  6. oHead.appendChild(oScript);
  7. }
This approach isn't without problems though. The request will load asynchronously which means that any JavaScript which depends on code returned by the request may continue to run before the request completes resulting in errors.

Callback event handlers

As described in far greater detail in JavaScript Madness: Dynamic Script Loading browsers provide the ability to specify a callback function to run once the script load completes. In most it's as simple as assigning a callback function to the script.onload event handler.
  1. oScript.onload = callback;
Internet Explorer, as in so many cases, does things differently. It supports a onreadystatechange event handler to which we can assign a callback function. It's slightly more complicated than that used by other browsers as one has to check a return status before running the callback.
  1. oScript.onreadystatechange = function() {
  2. if (this.readyState == 'complete') {
  3. callback();
  4. }
  5. }
Combining the parts gives us:
  1. function loadScript(sScriptSrc, oCallback) {
  2. var oHead = document.getElementById('head')[0];
  3. var oScript = document.createElement('script');
  4. oScript.type = 'text/javascript';
  5. oScript.src = sScriptSrc;
  6. // most browsers
  7. oScript.onload = oCallback;
  8. // IE 6 & 7
  9. oScript.onreadystatechange = function() {
  10. if (this.readyState == 'complete') {
  11. oCallback();
  12. }
  13. }
  14. oHead.appendChild(oScript);
  15. }

Detecting script load with timeouts

Reading a number of sources however it seems that there is a lack of trust in the cross browser robustness of these event handlers. One could instead use timeouts to poll for the existence of required functions returned by the script request and run our callback once detected.
I wrote the following function to achieve just this recently. The function takes two main parameters, a string representing the function to poll for and a reference to the callback function to run once it's found.
  1. function onFunctionAvailable(sMethod, oCallback, oObject, bScope) {
  2. if (typeof(eval(sMethod)) === 'function') {
  3. bScope ? oCallback.call(oObject) : oCallback(oObject);
  4. } else {
  5. setTimeout(function () {
  6. onFunctionAvailable(sMethod, oCallback, oObject, bScope);
  7. }), 50
  8. }
  9. }
Two additional parameters allow one to define the scope of "this" within the callback function.
The hardest part of this function was working out how to detect the existence of a function from a string. Fortunately there's no shortage of people I can turn to with JavaScript skills better than my own. Thanks toChristianStuart and Andrew for their input.

Further Reading

==================== READ FILES USING JS ========================
Example in Interenet Explorer: -

var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile("D:/test.txt", 1);
var fileContent = file.ReadAll();
file.Close();
alert(fileContent)
<script type="text/javascript" src="http://jqueryrotate.googlecode.com/svn/trunk/jQueryRotate.js"></script>
http://www.javascripter.net/faq/reading2.htm
http://www.htmlgoodies.com/beyond/javascript/read-text-files-using-the-javascript-filereader.html#fbid=58njQXyn5KO
http://msdn.microsoft.com/en-us/library/c0t5ef63(v=vs.85).aspx
http://www.w3.org/TR/FileAPI/#readingOnThreads
http://www.irt.org/xref/jscript_objects.htm **

http://jsbeautifier.org/
http://jquerybyexample.blogspot.com/2010/08/how-to-disable-right-click-using-jquery.html
http://www.wowslider.com/jquery-image-rotator-terse-blur-demo.html
==================== CROS ===================================

* Future Reading about JS
http://www.w3schools.com/jsref/jsref_obj_string.asp
http://blog.stevenlevithan.com/archives/high-performance-javascript
================= JQUERY EFFECTS ============ 

BOOK EFFECTS : -
http://builtbywill.com/code/booklet/
http://lab.smashup.it/flip/
http://www.webresourcesdepot.com/5-free-jquery-page-flip-plugins-for-book-like-interfaces/

<html>
<head>
<title>the title</title>
   <script type="text/javascript"  src="./booklet/jquery-1.7.2.min.js"></script>
   <script type="text/javascript"  src="./booklet/jquery-ui.min.js"></script>
   <script type="text/javascript"  src="./booklet/jquery.easing.1.3.js"></script>
   <script type="text/javascript"  src="./booklet/jquery.booklet.1.4.0.min.js"></script>
   <script type="text/javascript"  src="./booklet/jquery-ui-1.8.21.custom.min.js"></script>
<link href="./booklet/jquery.booklet.1.4.0.css" type="text/css" rel="stylesheet" media="screen, projection, tv" />

   <script type="text/javascript" language="javascript">  


  /*  $(document).ready(function() {
      $("#hide").click(function(){
         $(".target").hide( "fold",
                     {horizFirst: true }, 2000 );
      });
      $("#show").click(function(){
         $(".target").show( "fold",
                      {horizFirst: true}, 2000 );
      });
   });*/
   </script>
   <style>
      p {
           background-color:#bca;
           width:200px;
           border:1px solid green;
        }
     div{ width:100px;
            height:100px;
           
            /*background:#777;  */
        }
        .brd {
             border: solid;
        }
  </style>
</head>
<body>
<!--
   <p>Click on any of the buttons</p>
   <button id="hide"> Hide </button>
   <button id="show"> Show</button> 
   <div class="target"> </div>
   -->
   <br /><br />
<div id="mybook">
    <div class="brd">
       <h3>Yay, Page 1! Start</h3>

   </div>
  
   <div class="brd">
      <h3>Yay, Page 2! End of book</h3>
   </div>
   <!--
   <div>
      <h3>Yay, Page 3!</h3>
   </div>
   <div>
      <h3>Yay, Page 4!</h3>
   </div>
    <div>
      <h3>Yay, Page 5!</h3>
   </div>
    <div>
      <h3>Yay, Page 6!</h3>
   </div>
    <div>
      <h3>Yay, Page 7!</h3>
   </div>
    <div>
      <h3>Yay, Page 8!</h3>
   </div>
    <div>
      <h3>Yay, Page 9!</h3>
   </div>
    <div>
      <h3>Yay, Page 10!</h3>
   </div>
   -->
</div>
   <script type="text/javascript" language="javascript">  
  
   $(function() {
    //single book
    $('#mybook').booklet({closed:true});
   //multiple books with ID's
  // $('#mybook1, #mybook2').booklet();
   //multiple books with a class
    //$('.mycustombooks').booklet();
   });
   </script>
</body>
</html>
======================= GET SELECT VALUES ===========================
===============BY JQUERY:
$('select.foo option:selected').val();    // get the value from a dropdown select
$('select.foo').val();                    // get the value from a dropdown select even easier
$('input:checkbox:checked').val();        // get the value from a checked checkbox
$('input:radio[name=bar]:checked').val(); // get the value from a set of radio buttons

jQuery("form#testform").find("input[type='checkbox']:checked")
=======================================================================
===============QUERY STRING=================
var frm = document.forms['jagdeep'];
var queryString = frm.serialize();
window.location.search.parseQuery();
frm3.querySelector('input'); frm3.querySelectorAll('input');

================= OOPS -- EXAMPLE =====================
window.Employee = function(){
document.write("This is the default constructor.");
}
Employee.prototype.constructor = function(oneparam){
document.write("This is "+ oneparam +"constructor.");
}
Employee.prototype.constructor = function(oneparam,twoparam){
document.write("This is "+ oneparam+"--"+twoparam+"constructor.");
}
Employee.prototype.setName = function(name){
Employee.name = name;
}
Employee.prototype.getName = function(){
return this.name;
}

Trigger on change event on others

$('#select1').trigger('change');
CHECK DIV SHOW OR HIDE 
jQuery('#divID').is(':visible'))
AUTO HIDE DIV:
setTimeout(function() {
    $('#divID').fadeOut('slow');
}, 1000); 
SUBMIT FORM USING AJAX
//callback handler for form submit
$("#MYFORM").submit(function(e)
{
    var params= $(this).serializeArray();
    var action= $(this).attr("action");
    $.ajax(
    {
        url : action,
        type: "POST",
        data : params,
        success:function(data, textStatus, jqXHR) 
        {
            //data: return data from server on success fully complete the rquest
        },
        error: function(jqXHR, textStatus, errorThrown) 
        {
            //if found any error    
        }
    });
    e.preventDefault(); //STOP default action
});
 
$("#MYFORM").submit();

---------------------------------------------------------------
function uploadFormAction(_uvFrm,ext) {
  jQuery(_uvFrm).submit(function(e){  
    
    var formObj = jQuery(this);
    var _upFileVal = jQuery(formObj).find("#uploadedFile").attr('value');
    var reloadUrl = jQuery(formObj).find("#reloadUrl").attr('value');
    if(checkFileFormat(_upFileVal,ext)){    
    addAjaxLoader();
    var formURL = formObj.attr("action");
    var formData = new FormData(this);
    jQuery.ajax({
     url: formURL,
     type: 'POST',
     data:  formData,
     mimeType:"multipart/form-data",
     dataType: "JSON",
     contentType: false,
     cache: false,
     processData:false,
     success: function(data, textStatus, jqXHR) {
     
      removeAjaxLoader();
      var error = getServerError(data);
                 if (error != "") {
               
                  showErrorBox('Error: During submit the form.', 'ERROR', 'Ok', function(){
                  window.location.reload(reloadUrl); 
          });
                 } else if(data.resultStatus) { 
                
       showAlertBox(data.resultStatus, function(){
                 window.location.reload(reloadUrl); 
             });
      }else {
      
       showAlertBox("DONE", function(){
                 window.location.reload(reloadUrl); 
             });
      }       
     }, error: function(jqXHR, textStatus, errorThrown) {
      showErrorBox('Error: Some information is modified in the sheet, Please check the sheet.', 'ERROR', 'Ok', null);
     }          
    });
    }
    e.preventDefault();
   });
  }
---------------------------------------------------------------



jQuery(_uvFrm).submit(function(e){  
    var formObj = jQuery(this);   
    if(jQuery(formObj).valid()) {
    addAjaxLoader();
    var formURL = formObj.attr("action");
    var formData = new FormData(this);
    jQuery.ajax({
     url: formURL,
     type: 'POST',
     data:  formData,
     //mimeType:"multipart/form-data",
     dataType: "JSON",
     contentType: false,
     cache: false,
     processData:false,
     success: function(data, textStatus, jqXHR) {
      removeAjaxLoader();
      var error = getServerError(data);
                 if (error != "") {
                  showErrorBox('Error: During submit the form.', 'ERROR', 'Ok', function(){
                 
          });
                 }  else {                
       var _id = "#" + orderId.replace(/[^0-9A-Za-z_]/g, '');
       var _test =  jQuery(("#myTab a[href="+_id+"]"));
       if(_test && (_test.html() && _test.html()!="")){
        jQuery(_test).remove();
        jQuery(_id).remove();
        jQuery('#myTab a:last').tab('show');
        if(window.location.href.toString().indexOf("PO")!=-1 || window.location.href.toString().indexOf("procureNavigation")!=-1) 
         openLinkItem(orderId,baseURL+"viewpo?orderId="+orderId);
         else
          openLinkItem(orderId,baseURL+"orderDetail?orderId="+orderId);
       } else {
        window.location.reload();
       } 
      }  
     }, error: function(jqXHR, textStatus, errorThrown) {
      showErrorBox('Error: During submit the form.', 'ERROR', 'Ok', null);
     }          
    });    
    }
    e.preventDefault();
    
   });
HOW MAKE CUSTOM ALERT IN JS:-
window.alert = function(message) { 
  jQuery('<div class="custom-alert-container"/>').html(message).dialog({
         modal:true,
         title:'',
         buttons: {
             'OK':function(){
              jQuery(this).dialog('close');
             }
         },
         close:function(){ jQuery(this).dialog('destroy').remove(); }
     });
  jQuery(".custom-alert-container").parent().addClass("custom-alert-modal");
  
 };
DISABLE MOUSE WHEEL:-
 jQuery("input").bind("mousewheel", function(){return (jQuery.browser.webkit === true)?false:true;}});
DATA TABLE CONFIGURAION:- 

 jQuery('#sample_1').dataTable( {
    //paging position  setting
    "sDom": '<"top">rt<"bottom"flip>',
     "aoColumnDefs": [{
     'bSortable': false,
     'aTargets': [0]
    }],
     "bDestroy": true,
     "bFilter": false,
     "bRetrieve":   false,
     //hide columns and paginantion
    "order": [[ 0, "desc" ]],
         "paging":   false,
         "bPaginate": false,
         "bFilter": false,
   //change pagination
 "sPaginationType": "bootstrap",
            "oLanguage": {
                "sLengthMenu": "_MENU_ records per page",
                "oPaginate": {
                    "sPrevious": "Prev",
                    "sNext": "Next"
                }
            },   
  } ).fnDraw();























CODE FOR SHOW HIDE IMAGE

if(!document.getElementById(id)) {
  var divEl = document.createElement("div");
  divEl.setAttribute("id",id);  
  var imgEl = document.createElement("img");
  imgEl.setAttribute("id","hoverImgSrc");
  imgEl.setAttribute("src",imgSrc);
  divEl.appendChild(imgEl);
  document.body.appendChild(divEl);
 }
 if (Source=="1"){
  if (document.layers) document.layers[''+id+''].display = "block";
  else if (document.all) document.all[''+id+''].style.display = "block";
  else if (document.getElementById) document.getElementById(''+id+'').styledisplay = "block";
 } else if (Source=="0"){
  if (document.layers) document.layers[''+id+''].display = "none";
  else if (document.all) document.all[''+id+''].style.display = "none";
  else if (document.getElementById) document.getElementById(''+id+'').style.display = "none";
    }
 
 
Here it is in plugin format:
(function($)
{
    $.fn.removeStyle = function(style)
    {
        var search = new RegExp(style + '[^;]+;?', 'g');
        return this.each(function()
        {
            $(this).attr('style', function(i, style)
            {
                return style.replace(search, '');
            });
        });
    };
}(jQuery)); 

1 comment:

  1. its really helpfull for me thanks to Jagdeep who i s doing gr8 job in this Site.

    ReplyDelete