How to convert a javascript string into a html object using jQuery

$(var)

If we want to convert string tag to an html object we can do it using a jQuery function like this.

Javascript:

var stringTag  = '<input type="text" name="nameInput" id="idInput" />';
var htmlObject = $(stringTag);

And we could take this object and use it as an object.
Reference link: http://stackoverflow.com/questions/2522422/converting-a-javascript-string-to-a-html-object

How to check if value is “undefined” in Javascript

TypeOf

If we want to know if the value of a variable is “undefined” in javascript, we can use “typeof” javascript operator. It returns a string and it doesn’t generate an error if the variable doesn’t exist at all.

Javascript:

if( typeof value === "undefined" ){
    // ...
}

And we could define an specific method to check it:
Javascript:

function isUndefined(value){
    return ( typeof value === "undefined" );
}

var varName = "hello";
if( isUndefined(varName) ){
    //do this
}else{
    //do this
}

Reference link: http://stackoverflow.com/questions/10653367/how-to-check-undefined-value-in-jquery

How to get string data of inputs in DataTables rows

DataTables

Sometimes we have some problems to get data from a row in a table specially whe the data is an input tag likes checkbox, radio or text input. With fnGetData() we obtain an array of td’s of the row but in string format.

If we want to obtain all data of some cell of the row in an html format, we have to do this:

Javascript:

$(document).ready(function() {
  //datatable creation
  var oTable = $('#example').dataTable();

  //foreach rows of the table
  $(oTable.fnGetNodes()).each(function(index,elem)){
    var aPos  = oTable.fnGetPosition(this);
    var aData = oTable.fnGetData(aPos[0]);
    
    //we get array of strings
    var tdArray = aData[index];

    //now is the moment to convert our tr and td's tags into html tags
    var nRow = $('#example tbody tr:eq('+index+') td').parent('tr')[0];

    //and if we want to get only all the input tags
    var jqInputs = $('input', nRow);
    
    //and to go directly to an specific input of the row. For example in the cell number 1 this is a input
    var input = jqInputs[1];
    console.log(input);

    //and we have to get all attributes of the input
    console(input.name);
    console(input.value);

    //or using jQuery
    console.log('#' + input.id).val());
    console.log('#' + input.id).attr('yourAttribute');
    console.log('input[name["' + input.name + '"]').attr('yourAttribute');
    //know if input is cheched or not
    console.log('input[name["' + input.name + '"]').is(':checked');
  });
});

 

How to resize columns in datatables using callback method

Datatables

Sometimes we have some problems to configure the aspect of a datatable correctly for different reasons. I would like to you show how to solve it in an standard way.

After the table is loaded, it calls the callback method. And then we have to call to a fnAdjustColumnSizing in order to adjust all the columns in tha table. It’s important to enter only one time in this method. For this reason we have to control it adding an internal flag.

Javascript:

$(document).ready(function() {
  var isTableLoaded = false;
  var oTable = $('#example').dataTable( {
   "bAutoWidth": true, 
   "fnDrawCallback": function( oSettings ){
      if( !isTableLoaded){
           isTableLoaded = true;
           $('example').dataTable().fnAdjustColumnSizing();
      }
   }
  });
});

We can obtain more or less the same effect without calling a callback method but is better the first step:

$(document).ready(function() {
  var oTable = $('#example').dataTable( {
   "bAutoWidth": true
   }
  }).fnAdjustColumnSizing();

//Or

  var oTable = $('#example').dataTable( {
   "bAutoWidth": true
   }
  });
  oTable.fnAdjustColumnSizing();
});

Reference links: http://legacy.datatables.net/usage/callbacks

How to uncheck checkbox input value or array of input values with jquery

Checkbox input value

In this post I would like to show you how to uncheck input or array of inputs through input value:

  1. Example:
    Insert this input tag into body:

    <body>
       <input type="checkbox" name="cbname" value="test" checked="checked" />
    </body>
  2. To uncheck the checkbox if value is = to a variable for instance “test” you can do this:
    $('input:checkbox[value="test"]').attr('checked', false);
    //or
    $('input:checkbox[value="test"]').prop('checked', false);
  3. To uncheck array of inputs from object’s array or from json array:
    Example:

    <body>
       <input type="checkbox" name="personsName" id="" value="test1" checked="checked" />
       <input type="checkbox" name="personsName" id="" value="test2" checked="checked" />
    </body>


    If we have a json of strings first you have to use JSON.parse to create an object from a string

    var data = [{id: 1, cbvalue:'test1'}, {id: 2, cbvalue:'test2'}]
    var string = JSON.stringify(data)
    var objects = JSON.parse(data)

    Foreach loop and uncheck inputs

    objects.forEach(function(key, index){
      $('input:checkbox[value="' + key.cbvalue + '"]').attr('checked', false);
    });

Reference link: http://stackoverflow.com/questions/4957608/jquery-if-checkbox-value-test-uncheck

How to parse json array in javascript

Parse JSON

A common use of JSON is to read data from a web server, and display the data in a web page:

  1. JavaScript files needed:
    Insert these scripts into <head> tag:

    <head>
       //download this js from "http://jquery.com/download/"
       <script src="js/jquery.min.js"></script>
    </head>
  2. To convert object to string
    Use JSON.stringify to create a string from a object

    var data = [{id: 1, name:'personsName'}, {id: 2, name:'personsName2'}]
    var string = JSON.stringify(data)
  3. To convert string to object
    Use JSON.parse is to create an object from a string

    var data = [{id: 1, name:'personsName'}, {id: 2, name:'personsName2'}]
    var string = JSON.stringify(data)
    var objects = JSON.parse(data)

    Foreach loop

    objects.forEach(function(key, index){
      console.log(key.id);
      console.log(key.name); 
    });

Reference link: http://stackoverflow.com/questions/23068875/parse-json-array-in-jquery-in-foreach-loop

How to clone an object using JavaScript?

We can clone an array using this method:

  1. This is the JavaScript method:
    function clone(obj) {
       if(obj == null || typeof(obj) != 'object')
         return obj;
    
       var temp = {}; // changed
    
       for(var key in obj) {
         if(obj.hasOwnProperty(key)) {
           temp[key] = clone(obj[key]);
         }
       }
       return temp;
    }
  2. How to use it:
    var newObjList = [];
    for(var i=0; i< objList.length; i++){
        newObjList[i] = clone(objList[i]);
    };

Reference link: http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object

How to remove options from select using jQuery

We  can sort an array using this method:

  1. This is the select (HTML):
    <select name="selectBox" id="selectBox">
        <option value="option1">option1</option>
        <option value="option2">option2</option>
        <option value="option3">option3</option>
        <option value="option4">option4</option>	
    </select>
  2. How to remove the items. Just do:
    //Deleting all the items with value equals to 'X':
    $("#selectBox option[value='X']").each(function() {
        $(this).remove();
    });
    //Or:
    $("#selectBox option[value='X']").remove();

Reference link: http://stackoverflow.com/questions/375508/removing-an-item-from-a-select-box

How to sort an array of objects with javascript

We  can sort an array using this method:

  1. This is the method to sort the array:
    var array = [(name, artist),(name, artist),(name, artist)];
    
    function SortByName(a, b){
      var aName = a.name.toLowerCase();
      var bName = b.name.toLowerCase(); 
      return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
    }
    
    
  2. How to sort the array with data? Just do:
    var arr = [{name:'bob', artist:'rudy'},{name:'johhny', artist:'drusko'},{name:'tiff', artist:'needell'},{name:'top', artist:'gear'}];
    array.sort(SortByName);

Reference link: http://stackoverflow.com/questions/5503900/how-to-sort-an-array-of-objects-with-jquery-or-javascript

How to sort array on key value in javaScript using Prototype library

We  can sort a JSON  array using this method:

  1. This is the method to sort the array:
    Array.prototype.sortOn = function(key){
        this.sort(function(a, b){
            if(a[key] < b[key]){
                return -1;
            }else if(a[key] > b[key]){
                return 1;
            }
            return 0;
        });
    }
    
    
  2. How to sort the array with data? Just do:
    var arr = [{name:'bob', artist:'rudy'},{name:'johhny', artist:'drusko'},{name:'tiff', artist:'needell'},{name:'top', artist:'gear'}];
    arr.sortOn("name");
    arr.sortOn("artist");

If we want to convert the array to JSON we have to do this:

  1. var array = [];
    for ( var i=1 ; i< arr.length; i++ ){
            var mComponente = {
    	        name	: 'bob',
    	        artist  : 'rudy',
    	};
            array.push(mComponente);
    }
    
    // convert array into JSON array
    var jsonArray = $.parseJSON(JSON.stringify(array));
    

Reference link: http://stackoverflow.com/questions/16648076/sort-array-on-key-value