Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Monday, April 30, 2018

html table to excel js

<!-- using plugin with image -->
<!DOCTYPE html>
<html>
<head>
<title>jQuery Boilerplate</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="jquery.table2excel.js"></script> <!-- https://github.com/rainabba/jquery-table2excel -->
</head>
<body>
<table class="table2excel" data-tableName="Test Table 1">
<thead>
<tr class="noExl"><td>This shouldn't get exported</td><td>This shouldn't get exported either</td></tr>
<tr><td>This Should get exported as a header</td><td>This should too</td></tr>
</thead>
<tbody>
<tr>
<td>data1a with a <a href="#">link one</a> and <a href="#">link two</a>.</td>
<td>data1b with a <img src="image_file.jpg" alt="image">.</td></tr>
<tr>
<td>data2a with a <input tyle="text" value="text value">.</td>
<td>data2b with a <input tyle="text" value="second text value">.</td>
</tr>
</tbody>
<tfoot>
<tr><td colspan="2">This footer spans 2 cells</td></tr>
</tfoot>
</table>

<table class="table2excel" data-tableName="Test Table 2">
<thead>
<tr class="noExl"><td>This shouldn't get exported</td><td>This shouldn't get exported either</td></tr>
<tr><td>This Should get exported as a header</td><td>This should too</td></tr>
</thead>
<tbody>
<tr><td>data1a</td><td>data1b</td></tr>
<tr><td>data2a</td><td>data2b</td></tr>
</tbody>
<tfoot>
<tr><td colspan="2">This footer spans 2 cells</td></tr>
</tfoot>
</table>

<script>
$(function() {
$(".table2excel").table2excel({
exclude: ".noExl",
name: "Excel Document Name",
filename: "myFileName" + new Date().toISOString().replace(/[\-\:\.]/g, ""),
fileext: ".xls",
exclude_img: true,
exclude_links: true,
exclude_inputs: true
});
});
</script>
</body>
</html>

// using js
<!DOCTYPE html>
<html>
<head>
    <title>html table to excel</title>

    <script type="text/javascript">
        var tableToExcel = (function () {
            var uri = 'data:application/vnd.ms-excel;base64,'
                ,
                template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
                , base64 = function (s) {
                    return window.btoa(unescape(encodeURIComponent(s)))
                }
                , format = function (s, c) {
                    return s.replace(/{(\w+)}/g, function (m, p) {
                        return c[p];
                    })
                }
            return function (table, name) {
                if (!table.nodeType) table = document.getElementById(table)
                var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
                window.location.href = uri + base64(format(template, ctx))
            }
        })()
    </script>
    <style>
        table {
            empty-cells: show;
            border: 1px solid #000;
        }

        table td,
        table th {
            min-width: 2em;
            min-height: 2em;
            border: 1px solid #000;
        }
    </style>
</head>
<body>

    <input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">

<table  id="testTable">
    <tr>
        <td>
            Table heading
        </td>
    </tr>
    <tr>
        <td>
                <table>
        <thead>
        <tr>
            <th rowspan="2"></th>
            <th colspan="4">&nbsp;</th>
        </tr>
        <tr>
            <th>I</th>
            <th>II</th>
            <th>III</th>
            <th>IIII</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td></td>
            <td>1</td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
        </tr>
        <tr>
            <td>a</td>
            <td>1a</td>
            <td>2a</td>
            <td>3a</td>
            <td>a4</td>
        </tr>
        </tbody>
    </table>
        </td>
    </tr>
    <tr>
        <td>
                <table>
        <thead>
        <tr>
            <th rowspan="2"></th>
            <th colspan="4">&nbsp;</th>
        </tr>
        <tr>
            <th>I</th>
            <th>II</th>
            <th>III</th>
            <th>IIII</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td></td>
            <td>1</td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
        </tr>
        <tr>
            <td>a</td>
            <td>1a</td>
            <td>2a</td>
            <td>3a</td>
            <td>a4</td>
        </tr>
        </tbody>
    </table>
        </td>
    </tr>
</table>

    </body>
</html>



// form data to excel
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script type="text/javascript">

            $('input:radio').live('change', function(){
        var sstrSect = ($(this).attr('name').substr([3]));
    var comFldId = ("C" + sstrSect);
        if ($(this).val() == "NOK"){
            document.getElementById(comFldId).style.display = '';
        } else {
            document.getElementById(comFldId).style.display = 'none';
        }
    });

    $('input[type="radio"]:checked').each(function() {
        var sstrSect = ($(this).attr('name').substr([3]));
        var comFldId = ("C" + sstrSect);
            if ($(this).val() == "NOK"){
                document.getElementById(comFldId).style.display = '';
            } else {
                document.getElementById(comFldId).style.display = 'none';
            }
        });


function toExcel() {

    if ("ActiveXObject" in window) {
        alert("This is Internet Explorer!");
    } else {

        var cache = {};
        this.tmpl = function tmpl(str, data) {
            var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) :
            new Function("obj",
                         "var p=[],print=function(){p.push.apply(p,arguments);};" +
                         "with(obj){p.push('" +
                         str.replace(/[\r\t\n]/g, " ")
                         .split("{{").join("\t")
                         .replace(/((^|}})[^\t]*)'/g, "$1\r")
                         .replace(/\t=(.*?)}}/g, "',$1,'")
                         .split("\t").join("');")
                         .split("}}").join("p.push('")
                         .split("\r").join("\\'") + "');}return p.join('');");
            return data ? fn(data) : fn;
        };
        var tableToExcel = (function () {
            var uri = 'data:application/vnd.ms-excel;base64,',
                template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{{=worksheet}}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>{{for(var i=0; i<tables.length;i++){ }}<table>{{=tables[i]}}</table>{{ } }}</body></html>',
                base64 = function (s) {
                    return window.btoa(unescape(encodeURIComponent(s)));
                },
                format = function (s, c) {
                    return s.replace(/{(\w+)}/g, function (m, p) {
                        return c[p];
                    });
                };
            return function (tableList, name) {
                if (!tableList.length > 0 && !tableList[0].nodeType) table = document.getElementById(table);
                var tables = [];
                for (var i = 0; i < tableList.length; i++) {
                    tables.push(tableList[i].innerHTML);
                }
                var ctx = {
                    worksheet: name || 'Worksheet',
                    tables: tables
                };
                window.location.href = uri + base64(tmpl(template, ctx));
            };
        })();
        //tableToExcel(document.getElementsByTagName("table"), "one");
        tableToExcel(document.getElementsByClassName("testTable"), "one");
    }
}
    </script>
</head>
<body>
<input id="ExporttoExcel" class="show" type="button" onclick="toExcel()" value="Export to Excel">
<table class="testTable">
    <thead>
    <tr>
        <th rowspan="2"></th>
        <th colspan="4">&nbsp;</th>
    </tr>
    <tr>
        <th>I</th>
        <th>II</th>
        <th>III</th>
        <th>IIII</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td colspan="5">
            <table>
                <thead>
                <tr>
                    <th rowspan="2"></th>
                    <th colspan="4">&nbsp;</th>
                </tr>
                <tr>
                    <th>I</th>
                    <th>II</th>
                    <th>III</th>
                    <th>IIII</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td></td>
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                    <td>4</td>
                </tr>
                <tr>
                    <td>a</td>
                    <td>1a</td>
                    <td>2a</td>
                    <td>3a</td>
                    <td>a4</td>
                </tr>
                </tbody>

            </table>
        </td>
    </tr>
    <tr>
        <td colspan="5">
            <table>
                <thead>
                <tr>
                    <th rowspan="2"></th>
                    <th colspan="4">&nbsp;</th>
                </tr>
                <tr>
                    <th>I</th>
                    <th>II</th>
                    <th>III</th>
                    <th>IIII</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td></td>
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                    <td>4</td>
                </tr>
                <tr>
                    <td>a</td>
                    <td>1a</td>
                    <td>2a</td>
                    <td>3a</td>
                    <td>a4</td>
                </tr>
                </tbody>

            </table>
        </td>
    </tr>
    </tbody>
</table>

</body>
</html>


// multiple sheets

<!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/plain; charset=UTF-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Admin Panel</title>
<script type="text/javascript" >
  var tablesToExcel = (function() {
   var uri = 'data:application/vnd.ms-excel;base64,'
   , tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
     + '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>'
     + '<Styles>'
     + '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
     + '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
     + '</Styles>'
     + '{worksheets}</Workbook>'
   , tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>'
   , tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>'
   , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
   , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
   return function(tables, wsnames, wbname, appname) {
     var ctx = "";
     var workbookXML = "";
     var worksheetsXML = "";
     var rowsXML = "";
     for (var i = 0; i < tables.length; i++) {
       if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
       for (var j = 0; j < tables[i].rows.length; j++) {
         rowsXML += '<Row>'
         for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
           var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
           var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
           var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
           dataValue = (dataValue)?dataValue:tables[i].rows[j].cells[k].innerHTML;
           var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
           dataFormula = (dataFormula)?dataFormula:(appname=='Calc' && dataType=='DateTime')?dataValue:null;
           ctx = {  attributeStyleID: (dataStyle=='Currency' || dataStyle=='Date')?' ss:StyleID="'+dataStyle+'"':''
                  , nameType: (dataType=='Number' || dataType=='DateTime' || dataType=='Boolean' || dataType=='Error')?dataType:'String'
                  , data: (dataFormula)?'':dataValue
                  , attributeFormula: (dataFormula)?' ss:Formula="'+dataFormula+'"':''
                 };
           rowsXML += format(tmplCellXML, ctx);
         }
         rowsXML += '</Row>'
       }
       ctx = {rows: rowsXML, nameWS: wsnames[i] || 'Sheet' + i};
       worksheetsXML += format(tmplWorksheetXML, ctx);
       rowsXML = "";
     }
     ctx = {created: (new Date()).getTime(), worksheets: worksheetsXML};
     workbookXML = format(tmplWorkbookXML, ctx);
     var link = document.createElement("A");
     link.href = uri + base64(workbookXML);
     link.download = wbname || 'Workbook.xls';
     link.target = '_blank';
     document.body.appendChild(link);
     link.click();
     document.body.removeChild(link);
   }
 })();
</script>
</head>
<body>
<table id="tbl1" class="table2excel">
        <tr>
            <td>Product</td>
            <td>Price</td>
            <td>Available</td>
            <td>Count</td>
        </tr>
        <tr>
            <td>Bred</td>
            <td>1</td>
            <td>2</td>
             <td>3</td>
        </tr>
        <tr>
            <td>Butter</td>
            <td>4   </td>
            <td>5   </td>
            <td >6  </td>
        </tr>
  </table>
<hr>
  <table id="tbl2" class="table2excel">
        <tr>
            <td>Product</td>
            <td>Price</td>
            <td>Available</td>
            <td>Count</td>
        </tr>
        <tr>
            <td>Bred</td>
            <td>7</td>
            <td>8</td>
            <td>9</td>
        </tr>
        <tr>
            <td>Butter</td>
            <td>14</td>
            <td>15</td>
            <td >16</td>
        </tr>
    </table>
<button  onclick="tablesToExcel(['tbl1','tbl2'], ['ProductDay1','ProductDay2'], 'TestBook.xls', 'Excel')">Export to Excel</button>
</body>
</html>

Sunday, February 11, 2018

add row with sub child row

<!DOCTYPE html>
<html>
<head>
   <title>add row</title>
    <script type="text/javascript" src="multiple/jquery.min.js"></script>
</head>
<body>
<button onclick="main()">Pick</button>
<button onclick="del()">Delete</button>
<table>
   <thead>
        <tr>
            <th>select</th>
            <th>Item</th>
            <th>Sub Item</th>
        </tr>
    </thead>
    <tbody id="tbl">
        <tr>
            <td><input data-child="0" type="checkbox" name="ids[1]" id="ids_1"></td>
            <td><input type="text" name="item[1]" id="item_1"></td>
            <td>
                <input type="text" name="subitem[1]" id="subitem_1">
                <button onclick="sub(this.id)" id="pick_1">Pick Item</button>
            </td>
        </tr>
    </tbody>
</table>
</body>
</html>
<script type="text/javascript">
    function del() {
        if(parseInt($('#tbl input[type="checkbox"]:checked').length)>0){
            var selectedCheckbox=$('#tbl input[type="checkbox"]:checked');
            $.each(selectedCheckbox,function(index,val){
                if(parseInt($(val).attr('data-child'))>0){
                    var idArr=$(val).attr('id').split('_');
                    $('input[id^="ids_'+idArr[1]+'_"]').closest('tr').remove();
                } else {
                    $(val).closest('tr').remove();
                }
            });
        } else {
            alert('please select checkbox');
        }
        $('#tbl input[type="checkbox"]:checked').closest('tr').remove();
    }
    function main() {
        var trToCopy=$('#tbl tr:first').clone();
        var lastIdArr=$('#tbl tr:last td:first input').attr('id').split('_');
        var newId=parseInt(lastIdArr[1])+1;
        $('#tbl tr:last').after(trToCopy);
        var ids=$('#tbl tr:last [id]').after();
        $.each(ids,function(index,val){
            if($(val).attr('name')){
                var name = $(val).attr('name'),
                    name=name.replace(/\[[0-9]+\]/g, '['+newId+']');
                $(val).attr('name',name);
            }
            var oldId=$(val).attr('id').slice(0,-1);
            $(val).attr('id',oldId+newId);
        });
    }
    function sub(rowId) {
        var arr = [ "ids_", "subitem_"];
        var rowIdArr=rowId.split('_');
        var rowObj=$('#tbl input[type="checkbox"][id="ids_'+rowIdArr[1]+'"]').closest('tr');
        rowObj.after(rowObj.clone());
        var ids=rowObj.next().find('input,select,button');
        var newId=parseInt($('#tbl input[type="checkbox"][id="ids_'+rowIdArr[1]+'"]:first').attr('data-child'))+1;
        $.each(ids,function(index,val){
            var oldId=$(val).attr('id').slice(0,-1);
            if($.inArray(oldId, arr )>=0){
                if($(val).attr('name')){
                    var name = $(val).attr('name');
                    $(val).attr('name',name+'['+newId+']');
                }
                var oldId=$(val).attr('id');
                $(val).attr('id',oldId+'_'+newId);
                $(val).val('');
            } else {
                $(val).remove();
            }
        });
        $('#tbl input[type="checkbox"][id="ids_'+rowIdArr[1]+'"]').attr('data-child',newId);
    }
</script>

Sunday, November 27, 2016

Multiple JQuery Autocomplete With Selector

Multiple jquery autocomplete : example of multiple jquery autocomplete and also when select any element or hover on list description of hovered element will show and when we select the element its value will shown in lebel.

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>Multiple JQuery Autocomplete with selector</title>
      <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
      <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
      <!-- Javascript -->
      <script>
         $(function() {
            var projects = [
            {
               value: "java",
               label: "Java",
               desc: "write once run anywhere",
            },
            {
               value: "jquery-ui",
               label: "jQuery UI",
               desc: "the official user interface library for jQuery",
            },
            {
               value: "Bootstrap",
               label: "Twitter Bootstrap",
               desc: "popular front end frameworks ",
            }
         ];
            $("[id^=autocomplete_]").autocomplete({
               source: projects,
                focus: function( event, ui ) {
                    var idArr=$(this).attr('id').split('_');
                    $('#value_'+idArr[1]).text(ui.item.desc);
                        return false;
                },
                select: function( event, ui ) {
                    var idArr=$(this).attr('id').split('_');
                    $('#value_'+idArr[1]).text(ui.item.value);
                        return false;
                }

            });
         });
      </script>
   </head>
   <body>
      <!-- HTML -->
      <div class="ui-widget">
         <p>Type J OR b</p>
         <input id="autocomplete_1"><label id="value_1"></label><br>
         <input id="autocomplete_2"><label id="value_2"></label><br>
         <input id="autocomplete_3"><label id="value_3"></label><br>
         <input id="autocomplete_4"><label id="value_4"></label><br>
         <input id="autocomplete_5"><label id="value_5"></label><br
      </div>
   </body>
</html>

Friday, September 2, 2016

Clone table row and change attribute id

<!DOCTYPE html>
<html>
<head>
    <title>tbl row copy and change attribut id</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    /*$("#table-data").on('click', 'input.addButton', function() {
        var $tr = $(this).closest('tr');
        var allTrs = $tr.closest('table').find('tr');
        var lastTr = allTrs[allTrs.length-1];
        var $clone = $(lastTr).clone();
        $clone.find('td').each(function(){
            var el = $(this).find(':first-child');
            var id = el.attr('id') || null;
            if(id) {
                var i = id.substr(id.length-1);
                var prefix = id.substr(0, (id.length-1));
                el.attr('id', prefix+(+i+1));
                el.attr('name', prefix+(+i+1));
            }
        });
        $clone.find('input:text');
        $tr.closest('table').append($clone);
    });*/
 
    $("#table-data").on('change', 'select', function(){
        var val = $(this).val();
        $(this).closest('tr').find('input:text').val(val);
    });
});
function addrow(obj,ids){
    var t=$(obj);
    var idArr=ids.split('_');
    var $tr = t.closest('tr');
    var allTrs = $tr.closest('table').find('tr');
    var t=parseInt(idArr[1])+1;
    var lastTr = allTrs[t];
    var $clone = $(lastTr).clone();
    $clone.find('td').each(function(){
        var el = $(this).find(':first-child');
        var id = el.attr('id') || null;
        if(id) {
            var i = allTrs.length-2;
            var prefix = id.substr(0, (id.length-1));
            el.attr('id', prefix+(+i+1));
            el.attr('name', prefix+(+i+1));
        }
    });
    $clone.find('input:text');
    $tr.closest('table').append($clone);
}
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data">
    <tr>
        <td>SelectOne</td>
        <td>Select two</td>
        <td>TetxBox</td>
        <td>Select Three</td>
        <td>Add</td>
    </tr>
    <tr>
        <td>
            <select id="Id_0" name="Id.0">
                <option value=1>One</option>
                <option value=2>Two</option>
            </select>
        </td>
        <td>
            <select id="Comparator_0" name="Comparator.0">
                <option value=1>One</option>
                <option value=2>Two</option>
            </select>
        </td>
        <td><input type="text" id="Integer_0" name="Integer.0"/></td>
        <td>
            <select id="Value.0" name="Value.0">
                <option value=1>One</option>
                <option value=2>Two</option>
            </select>
        </td>
        <td><input type="button" id="btn_0" onclick="addrow(this,this.id)" class="addButton" value="Add" /></td>
    </tr>
</table>
</body>
</html>