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 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 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 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 select option in dropdown menu using jQuery

Sometimes we need to find the selected option in a select component.

HMTL

<select name=”options” id=”optionsById”>
      <option value=”1″>Red</option>
      <option value=”2″ selected=”1″>Green</option>
      <option value=”3″>Blue</option>
</select>


Javascript

//remove selected one
$(‘option:selected’, ‘select[name=”options”]’).removeAttr(‘selected’);
//Using the value by name
$(‘select[name=”options”]’).find(‘option[value=”3″]’).attr(“selected”,true);
//or
$(‘select[name=”options”]’).find(‘option[value=”3″]’).prop(“selected”,true);
//or
$(‘select[name=”options”]’).val(‘3’);
//Using the value by id
$(‘#optionsById option:eq(“1”)’).prop(“selected”,true);
//Using the text
$(‘select[name=”options”]’).find(‘option:contains(“Blue”)’).attr(“selected”,true);

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

jQuery form autofill

Simply autofill an empty form using JSON data:

  1. We need a form:
    <form id="f">
        name <input type="text" name="name">
        email <input type="text" name="email">
        love jQuery
        <input type="radio" name="lovejquery" value="yes"> yes
        <input type="radio" name="lovejquery" value="no"> no
    </form>
  2. and data:
    var data = {
        "name": "John Doe",
        "email": "johndoe@mail.com",
        "lovejquery": "yes"
    }
  3. How to autofill the form with data? Just do:
    $("#f").autofill( data );

Reference link: http://labs.creative-area.net/jquery.formautofill/doc/

How to convert an HTML Table into a JSON Object

Table-to-JSON

A jQuery plugin that converts an HTML Table into a javascript object. Great for working with user-editable tables or accessing output from 3rd party tools.:

  1. JavaScript files needed:

    Insert these scripts into <head> tag:

    <head>
       //download this js from "http://jquery.com/download/"
       <script src="js/jquery-1.9.1.min.js"></script>
    
       //download this js from "https://github.com/lightswitch05/table-to-json/blob/master/lib/jquery.tabletojson.min.js"
       <script src="js/jquery.tabletojson.min.js"></script>
    </head>
  2. Basic Usage JavaScript code:

    <head>
       //Insert this script into <head> tag:
       <script>
          //Basic Usage
          var table = $('#example-table').tableToJSON();
       </script>
    </head>
  3. Advance Usage JavaScript code:
    <head>
       //Insert this script into <head> tag
       <script>
          //Ignore first column (name)
          var table = $('#example-table').tableToJSON({
            ignoreColumns: [0]
          });
       </script>
    </head>
  4. Example:
    First Name Last Name Points
    Jill Smith 50
    Eve Jackson 94
    John Doe 80
    Adam Johnson 67
    HMTL
    <table id='example-table'>
      <thead>
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th data-override="Score">Points</th></tr>
      </thead>
      <tbody>
        <tr>
          <td>Jill</td>
          <td>Smith</td>
          <td data-override="disqualified">50</td></tr>
        <tr>
          <td>Eve</td>
          <td>Jackson</td>
          <td>94</td></tr>
        <tr>
          <td>John</td>
          <td>Doe</td>
          <td>80</td></tr>
        <tr>
          <td>Adam</td>
          <td>Johnson</td>
          <td>67</td></tr>
      </tbody>
    </table>
  5. Result of the example:

    <script type="text/javascript">
      // Basic Usage
      var table = $('#example-table').tableToJSON();
      // table == [{"First Name"=>"Jill", "Last Name"=>"Smith", "Score"=>"disqualified"},
      //           {"First Name"=>"Eve", "Last Name"=>"Jackson", "Score"=>"94"},
      //           {"First Name"=>"John", "Last Name"=>"Doe", "Score"=>"80"},
      //           {"First Name"=>"Adam", "Last Name"=>"Johnson", "Score"=>"67"}]
    
      // Ignore first column (name)
      var table = $('#example-table').tableToJSON({
            ignoreColumns: [0]
      });
      // table == [{"Last Name"=>"Smith", "Score"=>"disqualified"},
      //           {"Last Name"=>"Jackson", "Score"=>"94"},
      //           {"Last Name"=>"Doe", "Score"=>"80"},
      //           {"Last Name"=>"Johnson", "Score"=>"67"}]
    </script>

Reference link: http://lightswitch05.github.io/table-to-json/

ENCODE AND DECODE JSON TEXT FROM JAVA TO JAVASCRIPT – USING MAP

JSON.simple is a simple Java toolkit for JSON. You can use JSON.simple to encode or decode JSON text.

  1. Mapping between JSON and JAVA entities:
    JSON Java
    object java.util.Map
  2. Example:
    //import org.json.simple.JSONValue;
    Encode a java.util.List in Java
    Java:

      Map<String, String> obj = new LinkedHashMap()<String, String>;
      obj.put("name","foo");
      obj.put("num",new Integer(100));
      obj.put("balance",new Double(1000.21));
      obj.put("is_vip",new Boolean(true));
      obj.put("nickname",null);
    
      String jsonText = JSONValue.toJSONString(obj);

    Decode it in JavaScript using LinkedHashMap

    JavaScript:

      var js_obj = JQuery.parseJSON(jsonText);
      // or var js_obj = JSON.parse(jsonText);
      var name = js_obj[name];
      var num = js_obj[num];
    
      // to see if key exists
      var key = "name";
      if( key in js_obj )

Reference Link: https://code.google.com/p/json-simple/
Reference Link: http://api.jquery.com/jQuery.parseJSON/
Reference Link: http://www.jquerysdk.com/api/jQuery.toJSON