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>

Monday, November 14, 2016

infinite load more data at page end

<!DOCTYPE html>
<html>
<head>
    <title>Loading</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <style type="text/css">
        .loadedcontent {min-height: 800px; }
    </style>
</head>
<body>
<input type="hidden" value="0" id="numCount"></input>
<div id="container">
    <div style="border:1px solid" class="loadedcontent">old div</div>
</div>

</body>
</html>
<script type="text/javascript">
var processing;

$(document).ready(function(){
    $(document).scroll(function(e){
        if (processing){
            return false;
        }

        if ($(window).scrollTop() >= ($(document).height() - $(window).height())*0.7){
            processing = true;
            var numCount=$("#numCount").val();
            numCount++;
            var data1='<div class="loadedcontent">new div'+numCount+'</div>';
            //var sortData = $('#productsearchid').serialize();
            //var sortData = {};
            //sortData['category_name'] = 'electronics';
            //$.ajax({
            //    url:"load_data.php",
            //    cache:false,
            //    type:'GET',
            //    data:sortData,
                //success:function(data){
                    $('#container').append(data1);
                    $("#numCount").val(numCount)
                    processing = false;
                //}
            //});
        }
    });
});
</script>

Saturday, November 5, 2016

call js function when user stop typing

Many times we need instant result of whatever the change has been made. For calculation we define some function and do calculation there or for search we do ajax call. But for result we we call our function /ajax on every keyup event then what happen if i have to search a name "gautam" then then function calls 6 times as each keyup but 5 call is a waste as i am searching for "gautam" not for each character as typed.

In short we should call our function or ajax request when user stop typing not on each and every key up. For it we may guess when user type halts for a second or two second then his typing is finished and we can do whatever the result he wants.

<!DOCTYPE html>
<html>
<head>
    <title>call js function when stop typing</title>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $('document').ready(function() {
        $('#in').keyup(function() {
            s = $('#in').val();
            setTimeout(function() {
                if($('#in').val() == s){ // Check value is last typed or not.
                    // call ajax or any function or whaterver you wnat
                    var v = $("#in").val();
                    $("#out").html(v);
                }
            }, 1000); // 1 sec delay to check.
        });
    });

    </script>
</head>
<body>
<input id="in" type="text"/>
<div id="out"></div>
</body>
</html>


<!DOCTYPE html>
<html>
<head>
    <title>call js function when stop typing</title>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    var typingTimer;                //timer identifier
    var doneTypingInterval = 1000;  //time in ms, 5 second for example

    //on keyup, start the countdown
    $('document').ready(function(){
        $('#in').keyup(function(){
            clearTimeout(typingTimer);
            if ($('#in').val) {
                typingTimer = setTimeout(function(){
                    //do stuff here e.g ajax call etc....
                    var v = $("#in").val();
                    $("#out").html(v);
                }, doneTypingInterval);
            }
        });      
    });

    </script>
</head>
<body>
<input id="in" type="text"/>
<div id="out"></div>
</body>
</html>

Monday, September 12, 2016

call any other element property function from another function

Call any other function defined with own argument from another function by reading the property.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
function checkFun(i,name,code){
if(document.getElementById('name_'+i).checked==true){
console.log('checked '+i+' '+name+' '+code);
} else {
console.log('not checked '+i+' '+name+' '+code);
}
}
function checkAll(ths){
var k=$(ths);
if(k.prop('checked')==true){
for(var i=1;i<=document.getElementsByName('ids[]').length;i++){
var t=$('#name_'+i);
var funArgList=t.attr('onClick');
var funArgListArr1=funArgList.replace(/[('",)]/g,'_');
funArgListArr1=funArgListArr1.replace(/_+/g, '_');
var funArgListArr2=funArgListArr1.split('_');
if(document.getElementById('name_'+funArgListArr2[1]).checked==false){
document.getElementById('name_'+funArgListArr2[1]).checked=true;
checkFun(funArgListArr2[1],funArgListArr2[2],funArgListArr2[3]);
} else {
continue;
}

}
} else {
for(var i=1;i<=document.getElementsByName('ids[]').length;i++){
document.getElementById('name_'+i).checked=false;
}
}

}
</script>
</head>
<body>
<table>
<tr>
<td><input onclick="checkAll(this)" id="name_0" type="checkbox" name="" value="" /></td>
<td id="name_0">Select All</td>
</tr>
<tr>
<td><input onclick="checkFun('1','name1 h','code1')" id="name_1" type="checkbox" name="ids[]" value="" /></td>
<td id="name_1">name1</td>
</tr>
<tr>
<td><input onclick="checkFun('2','name2','code2')" id="name_2" type="checkbox" name="ids[]" value="" /></td>
<td id="name_2">name2</td>
</tr>
<tr>
<td><input onclick="checkFun('3','name3','code3')" id="name_3" type="checkbox" name="ids[]" value="" /></td>
<td id="name_3">name3</td>
</tr>
<tr>
<td><input onclick="checkFun('4','name4','code4')" id="name_4" type="checkbox" name="ids[]" value="" /></td>
<td id="name_4">name4</td>
</tr>
<tr>
<td><input onclick="checkFun('5','name5','code5')" id="name_5" type="checkbox" name="ids[]" value="" /></td>
<td id="name_5">name5</td>
</tr>
<tr>
<td><input onclick="checkFun('6','name6','code6')" id="name_6" type="checkbox" name="ids[]" value="" /></td>
<td id="name_6">name6</td>
</tr>
<tr>
<td><input onclick="checkFun('7','name7','code7')" id="name_7" type="checkbox" name="ids[]" value="" /></td>
<td id="name_7">name7</td>
</tr>
</table>
</body>
</html>

Friday, September 2, 2016

Wordwrap in fpdf table cell

Adding word wrap feature while creating pdf file using fpdf table cell data .
Complete source ccode is at end.
<?php
require('mc_table.php');

class PDF extends FPDF
{
// Load data
function LoadData($file)
{
// Read file lines
$lines = file($file);
$data = array();
foreach($lines as $line)
$data[] = explode(';',trim($line));
return $data;
}

// Simple table
function BasicTable($header, $data)
{
// Header
foreach($header as $col)
$this->Cell(40,7,$col,1);
$this->Ln();
// Data
foreach($data as $row)
{
foreach($row as $col)
$this->Cell(40,6,$col,1);
$this->Ln();
}
}

// Better table
function ImprovedTable($header, $data)
{
// Column widths
$w = array(40, 35, 40, 45);
// Header
for($i=0;$i<count($header);$i++)
$this->Cell($w[$i],7,$header[$i],1,0,'C');
$this->Ln();
// Data
foreach($data as $row)
{
$this->Cell($w[0],6,$row[0],'LR');
$this->Cell($w[1],6,$row[1],'LR');
$this->Cell($w[2],6,number_format($row[2]),'LR',0,'R');
$this->Cell($w[3],6,number_format($row[3]),'LR',0,'R');
$this->Ln();
}
// Closing line
$this->Cell(array_sum($w),0,'','T');
}

// Colored table
function FancyTable($header, $data)
{
// Colors, line width and bold font
$this->SetFillColor(255,0,0);
$this->SetTextColor(255);
$this->SetDrawColor(128,0,0);
$this->SetLineWidth(.3);
$this->SetFont('','B');
// Header
$w = array(40, 35, 40, 45);
for($i=0;$i<count($header);$i++)
$this->Cell($w[$i],7,$header[$i],1,0,'C',true);
$this->Ln();
// Color and font restoration
$this->SetFillColor(224,235,255);
$this->SetTextColor(0);
$this->SetFont('');
// Data
$fill = false;
foreach($data as $row)
{
$this->Cell($w[0],6,$row[0],'LR',0,'L',$fill);
$this->Cell($w[1],6,$row[1],'LR',0,'L',$fill);
$this->Cell($w[2],6,number_format($row[2]),'LR',0,'R',$fill);
$this->Cell($w[3],6,number_format($row[3]),'LR',0,'R',$fill);
$this->Ln();
$fill = !$fill;
}
// Closing line
$this->Cell(array_sum($w),0,'','T');
}
}

function GenerateWord()
{
//Get a random word
$nb=rand(3,10);
$w='';
for($i=1;$i<=$nb;$i++)
$w.=chr(rand(ord('a'),ord('z')));
return $w;
}

function GenerateSentence()
{
//Get a random sentence
$nb=rand(1,10);
$s='';
for($i=1;$i<=$nb;$i++)
$s.=GenerateWord().' ';
return substr($s,0,-1);
}

$pdf=new PDF_MC_Table();
$pdf->AddPage();
$pdf->SetFont('Arial','',14);
//Table with 20 rows and 4 columns
$pdf->SetWidths(array(30,50,30,40));
srand(microtime()*1000000);
/*for($i=0;$i<20;$i++){
$pdf->Row(array(GenerateSentence(),GenerateSentence(),GenerateSentence(),GenerateSentence()));
}*/
$pdf1 = new PDF();
$data = $pdf1->LoadData('countries.txt');
//print_r($data);
$i=0;
foreach ($data as $key => $value) {
$pdf->Row(array($i++.' '.$value[0],$value[1],$value[2],$value[3]));
}
$pdf->Output();
?>

Source Code

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>

Saturday, July 9, 2016

js validation in a form and set focus


<html>
<head>
<script type="text/javascript">

function validate(){
var eduInput = document.getElementsByName('edu[]');
var name4=document.getElementById('name4').value;
for (i=0; i<eduInput.length; i++) {
if (eduInput[i].value == "")
{
alert('Complete all the fields');
document.getElementById(eduInput[i].id).focus();
return false;
}
}
if(name4==''){
alert('Enter name field');
document.getElementById('name4').focus();
return false;
}
}

</script>
</head>
<body>
<form onsubmit="return validate()">
Education:<br>
<input type="text" name="edu[]" id="name1" placeholder="name array fields" /><br>
<input type="text" name="edu[]" id="name2" placeholder="name array fields" /><br>
<input type="text" name="edu[]" id="name3" placeholder="name array fields" /><br>
<input type="text" name="edu" id="name4" placeholder="name" /><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

using page break in print content

to print content with new page or putting a page break in the page we use css styling.
syntax: page-break-after: auto|always|avoid|left|right|initial|inherit;

Property Values

Value Description
auto(Default) Automatic page breaks
always Always insert a page break after the element
avoid Avoid page break after the element (if possible)
left Insert page breaks after the element so that the next page is formatted as a left page
right Insert page breaks after the element so that the next page is formatted as a right page
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

example:
@media print {
    .newPageClass{ page-break-after: always; }
}
and use this class in the div after which you want a page break while printing the page

Monday, July 4, 2016

js to print only a specific div

We always have to print a page. Many time we create a separate page for print but by using this code we can print any div. Just we need to put an id in the div and while calling the print function pass this id and cheers.....................


<div id="printableArea">
      <h1>Print me</h1>
</div>

<input type="button" value="Print" class="submitbutton" onClick="printContent('feePrint');">

<script type="text/javascript">
function printContent(el){
var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);
}
</script>