Friday, 27 June 2014

Overriding Vs Hiding

Can I override a static method?
Many people have heard that you can't override a static method. This is true - you can't. However it is possible to write code like this:

class Foo {
    public static void method() {
        System.out.println("in Foo");
    }
}

class Bar extends Foo {
    public static void method() {
        System.out.println("in Bar");
    }
}
This compiles and runs just fine. Isn't it an example of a static method overriding another static method? The answer is no - it's an example of a static method hiding another static method. If you try to override a static method, the compiler doesn't actually stop you - it just doesn't do what you think it does.
So what's the difference?
Briefly, when you override a method, you still get the benefits of run-time polymorphism, and when you hide, you don't. So what does that mean? Take a look at this code:

class Foo {
    public static void classMethod() {
        System.out.println("classMethod() in Foo");
    }

    public void instanceMethod() {
        System.out.println("instanceMethod() in Foo");
    }
}

class Bar extends Foo {
    public static void classMethod() {
        System.out.println("classMethod() in Bar");
    }

    public void instanceMethod() {
        System.out.println("instanceMethod() in Bar");
    }
}

class Test {
    public static void main(String[] args) {
        Foo f = new Bar();
        f.instanceMethod();
        f.classMethod();
    }
}
If you run this, the output is
instanceMethod() in Bar
classMethod() in Foo
Why do we get instanceMethod from Bar, but classMethod() from Foo? Aren't we using the same instance f to access both of these? Yes we are - but since one is overriding and the other is hiding, we see different behavior.
Since instanceMethod() is (drum roll please...) an instance method, in which Bar overrides the method from Foo, at run time the JVM uses the actual class of the instance f to determine which method to run. Although f was declared as a Foo, the actual instance we created was a new Bar(). So at runtime, the JVM finds that f is a Bar instance, and so it calls instanceMethod() in Bar rather than the one in Foo. That's how Java normally works for instance methods.
With classMethod() though. since (ahem) it's a class method, the compiler and JVM don't expect to need an actual instance to invoke the method. And even if you provide one (which we did: the instance referred to by f) the JVM will never look at it. The compiler will only look at the declared type of the reference, and use that declared type to determine, at compile time, which method to call. Since f is declared as type Foo, the compiler looks at f.classMethod() and decides it means Foo.classMethod. It doesn't matter that the instance reffered to by f is actually a Bar - for static methods, the compiler only uses the declared type of the reference. That's what we mean when we say a static method does not have run-time polymorphism.
Because instance methods and class methods have this important difference in behavior, we use different terms - "overriding" for instance methods and "hiding" for class methods - to distinguish between the two cases. And when we say you can't override a static method, what that means is that even if you write code that looks like it's overriding a static method (like the first Foo and Bar at the top of this page) - it won't behave like an overridden method.
So what about accessing a static method using an instance?
It's possible in Java to write something like:
   f.classMethod();
where f is an instance of some class, and classMethod() is a class method (i.e. a static method) of that class. This is legal, but it's a bad idea because it creates confusion. The actual instance f is not really important here. Only thedeclared type of f matters. That is, what class is f declared to be? Since classMethod() is static, the class of f (as determined by the compiler at compile time) is all we need.
Rather than writing:
    f.classMethod();
It would be better coding style to write either:
    Foo.classMethod();
or
    Bar.classMethod(); 
That way, it is crystal clear which class method you would like to call. It is also clear that the method you are calling is indeed a class method.
Barring that, you could always come up with this monstrosity:
    f.getClass().getMethod("classMethod", new Class[]).invoke(null, new Object[]);
But all this could be avoided by simply not trying to override your static (class) methods. :-)
Why does the compiler sometimes talk about overriding static methods?
Sometimes you will see error messages from the compiler that talk about overriding static methods. Apparently, whoever writes these particular messages has not read the Java Language Specification and does not know the difference between overriding and hiding. So they use incorrect and misleading terminology. Just ignore it. The Java Language Specification is very clear about the difference between overriding and hiding, even if the compiler messages are not. Just pretend that the compiler said "hide" rather than "override"..

Thursday, 19 June 2014

zoomIn and zoomout

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
<script>
  var fontSize = 1;
function zoomIn() {
    fontSize += 0.1;
    document.body.style.fontSize = fontSize + "em";
}
function zoomOut() {
    fontSize -= 0.1;
    document.body.style.fontSize = fontSize + "em";
}
</script>
 </head>
 <body>
<input type="button" value="+" onClick="zoomIn()"/>
<input type="button" value="-" onClick="zoomOut()"/>
 </body>
</html>

Validation for enter numeric value only using scripting

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <script>
function validate(evt) {

  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
 alert("Enter numeric only...");
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
  }
</script>
 </head>

 <body>
  Enter Your ID <input type="text" value="" onkeypress='validate(event)'/>
 </body>
</html>

Auto calculate

<html>
    <head>
        <title>Sum Html Textbox Values using jQuery/JavaScript</title>
        <style>
            body {
                font-family: sans-serif;
            }
            #summation {
                font-size: 18px;
                font-weight: bold;
                color:#174C68;
            }
            .txt {
                background-color: #FEFFB0;
                font-weight: bold;
                text-align: right;
            }
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    </head>
    <body>
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">
    <tr>
        <td width="40px">1</td>
        <td>Butter</td>
        <td><input class="txt" type="text" name="txt"/></td>
    </tr>
    <tr>
        <td>2</td>
        <td>Cheese</td>
        <td><input class="txt" type="text" name="txt"/></td>
    </tr>
    <tr>
        <td>3</td>
        <td>Eggs</td>
        <td><input class="txt" type="text" name="txt"/></td>
    </tr>
    <tr>
        <td>4</td>
        <td>Milk</td>
        <td><input class="txt" type="text" name="txt"/></td>
    </tr>
    <tr>
        <td>5</td>
        <td>Bread</td>
        <td><input class="txt" type="text" name="txt"/></td>
    </tr>
    <tr>
        <td>6</td>
        <td>Soap</td>
        <td><input class="txt" type="text" name="txt"/></td>
    </tr>
    <tr id="summation">
        <td>&nbsp;</td>
        <td align="right">Sum :</td>
        <td align="center"><span id="sum">0</span></td>
    </tr>
</table>


<script>
    $(document).ready(function(){

        //iterate through each textboxes and add keyup
        //handler to trigger sum event
        $(".txt").each(function() {

            $(this).keyup(function(){
                calculateSum();
            });
        });

    });

    function calculateSum() {

        var sum = 0;
        //iterate through each textboxes and add the values
        $(".txt").each(function() {

            //add only if the value is number
            if(!isNaN(this.value) && this.value.length!=0) {
                sum += parseFloat(this.value);
            }

        });
        //.toFixed() method will roundoff the final sum to 2 decimal places
        $("#sum").html(sum.toFixed(2));
    }
</script>
</body>
</html>

Sample code for getting popup

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Popup Dialog - Click</title>
<style type="text/css">
#overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
filter:alpha(opacity=70);
-moz-opacity:0.7;
-khtml-opacity: 0.7;
opacity: 0.7;
z-index: 100;
display: none;
}
.content a{
text-decoration: none;
}
.popup{
width: 100%;
margin: 0 auto;
display: none;
position: fixed;
z-index: 101;
}
.content{
min-width: 600px;
width: 600px;
min-height: 150px;
margin: 100px auto;
background: #f3f3f3;
position: relative;
z-index: 103;
padding: 10px;
border-radius: 5px;
box-shadow: 0 2px 5px #000;
}
.content p{
clear: both;
color: #555555;
text-align: justify;
}
.content p a{
color: #d91900;
font-weight: bold;
}
.content .x{
float: right;
height: 35px;
left: 22px;
position: relative;
top: -25px;
width: 34px;
}
.content .x:hover{
cursor: pointer;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type='text/javascript'>
$(function(){
var overlay = $('<div id="overlay"></div>');
$('.close').click(function(){
$('.popup').hide();
overlay.appendTo(document.body).remove();
return false;
});

$('.x').click(function(){
$('.popup').hide();
overlay.appendTo(document.body).remove();
return false;
});

$('.click').click(function(){
overlay.show();
overlay.appendTo(document.body);
$('.popup').show();
return false;
});
});
</script>
</head>
<body>
<div class='popup'>
<div class='content'>
<img src='http://www.developertips.net/demos/popup-dialog/img/x.png' alt='quit' class='x' id='x' />
<p>
<h1 align="center">Thank You for visiting my blog</h1>
<br/>
<br/>
<h1 align="center"><button><a href='' class='close'>OK</a></button></h1>
</p>
</div>
</div>        
<div id='container'>
<a href='' class='click'><h2><b>Click Here to See Popup! </b></h2></a> <br/>
</div>
</body>
</html>

Wednesday, 18 June 2014

convert & to & and & to &

/*jsoup-1.7.3.jar,apache-commons-lang.jar download these jar for executing below example

*/
import org.apache.commons.lang.StringEscapeUtils;
import org.jsoup.Jsoup;
public class testEscapeHTML{

public static void main(String args[]){

String testStr = "yogi 1 & 2";

System.out.println("Original : " + testStr);
String str=StringEscapeUtils.escapeHtml(testStr);
System.out.println("Escaped : "+str);
String s = Jsoup.parse(str).text();
        System.out.print("After convertion : "+s);

}
}

Link for patterns in C

http://www.cprogramto.com/c-program-to-print-pyramid/ 

Saturday, 14 June 2014

code for Encryption and Decryption using java

>javac  DESEncryption.java
>java  DESEncryption


import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESEncryption {

    private static final String UNICODE_FORMAT = "UTF8";
    public static final String DES_ENCRYPTION_SCHEME = "DES";
    private KeySpec myKeySpec;
    private SecretKeyFactory mySecretKeyFactory;
    private Cipher cipher;
    byte[] keyAsBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    SecretKey key;

    public DESEncryption() throws Exception
    {
        myEncryptionKey = "ThisIsSecretEncryptionKey";
        myEncryptionScheme = DES_ENCRYPTION_SCHEME;
        keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        myKeySpec = new DESKeySpec(keyAsBytes);
        mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = mySecretKeyFactory.generateSecret(myKeySpec);
    }

    /**
     * Method To Encrypt The String
     */
    public String encrypt(String unencryptedString) {
        String encryptedString = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            byte[] encryptedText = cipher.doFinal(plainText);
            BASE64Encoder base64encoder = new BASE64Encoder();
            encryptedString = base64encoder.encode(encryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedString;
    }
    /**
     * Method To Decrypt An Ecrypted String
     */
    public String decrypt(String encryptedString) {
        String decryptedText=null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, key);
            BASE64Decoder base64decoder = new BASE64Decoder();
            byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
            byte[] plainText = cipher.doFinal(encryptedText);
            decryptedText= bytes2String(plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptedText;
    }
    /**
     * Returns String From An Array Of Bytes
     */
    private static String bytes2String(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i<bytes.length; i++) {
            stringBuffer.append((char) bytes[i]);
        }
        return stringBuffer.toString();
    }

    /**
     * Testing the DES Encryption And Decryption Technique
     */
    public static void main(String args[]) throws Exception
    {
        DESEncryption myEncryptor= new DESEncryption();

        String stringToEncrypt="Sanjaal.com";
        String encrypted=myEncryptor.encrypt(stringToEncrypt);
        String decrypted=myEncryptor.decrypt(encrypted);

        System.out.println("String To Encrypt: "+stringToEncrypt);
        System.out.println("Encrypted Value :" + encrypted);
        System.out.println("Decrypted Value :"+decrypted);

    }

}

Friday, 13 June 2014

Code for escape special characters from script

<html>
   <body>
      Enter name <input type="" value="abc%#%$#&&" >
 <input type="submit" value="submit" onClick="escapeCharacter(this.value)">
   </body>
</html>
Note: If you are sending data through javaScript or scripting languages to java class then it will not print entire text value (like abc%#%$#&&). bcz,it will not allow special characters (like %#%$#&&).
Solution: We have to escape special characters (like %#%$#&&) by using "escape(String)".

Ex:
function escapeCharacter(val)
{
var value=val;
var escapeVal=escape("value");
var url = "urlToSendData.action?valueToSend="+escapeVal;
}

Validation for not allowing special symbols except _@./#&+- (if u remove _@./#&+- from code those characters also not allowed)


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Regex to allow special characters, spaces and alphanumeric</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function() {
$('#btnValidate').click(function() {
var txt = $('#txtdesc').val();
var re = /^[ A-Za-z0-9_@./#&+-]*$/
if (re.test(txt)) {
alert('Valid Text')
}
else {
alert('Please dnt enter special symbols');
return false;
}
})
})
</script>
</head>
<body>
<div>
Enter Text :<input type="text" id="txtdesc" />
<input type="button" id="btnValidate" value="Validate" />
</div>
</body>
</html>

Validation for enter only numeric and it will display when entering values

<html>
<head>
<script>
function validate(evt) {

  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
 alert("Enter numeric only...");
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
  }
</script>
</head>

<body>
Enter  value : <input type='text' onkeypress='validate(event)' />
</body>

</html>

Tuesday, 10 June 2014

Graph chart code for getting reports by column chart

 
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
 
<script type="text/javascript">
//Column Chart
$(function () {

var percentage=document.getElementById('percentage').value;
var examname=document.getElementById('examname').value;
//alert(percentage);alert(examname);

var percentage1 =percentage.split("~");
      var examname1 = examname.split("~");
      var exam=[],percent=[];
      for (var i=0;i<examname1.length;i++)
{
exam[i]=examname1[i];
percent[i]=percentage1[i];
}
//alert(exam);alert(percent);
        $('#container').highcharts({
            chart: {
                        backgroundColor: {
                linearGradient: [0, 0, 500, 500],
                stops: [
                    [0, 'rgb(255, 255, 255)'],
                    [1, 'rgb(200, 200, 255)']
                ]
            },
            borderColor: '#EBBA95',
            borderWidth: 2,
                type: 'column',
                margin: [ 50, 50, 100, 80]
            },
            title: {
                text: 'Library Month Wise Report...'
            },
            xAxis: {
                categories:exam,
                labels: {
                    rotation: -45,
                    align: 'right',
                    style: {
                   
                        fontSize: '13px',
                        fontFamily: 'Verdana, sans-serif'
                    }
                },
                 title: {
                    text: '<br/>Exam Names'
                }
            },
           
            yAxis: {
            gridLineColor: '#197F07',
            gridLineWidth: 2,
                min: 0,
                title: {
                    text: 'Books'
                }
            },
            legend: {
                enabled: false
            },
            tooltip: {
                pointFormat: 'Marks: <b>{point.y:.1f} %</b>',
            },
            series: [{
                name: 'Percentage',
                data: JSON.parse("["+percent+"]"),
                dataLabels: {
                    enabled: true,
                    rotation: -90,
                    color: '#FFFFFF',
                    align: 'right',
                    x: 4,
                    y: 10,
                    style: {
                        fontSize: '13px',
                        fontFamily: 'Verdana, sans-serif',
                        textShadow: '0 0 3px black'
                    }
                }
            }],
            navigation: {
            buttonOptions: {
                text:"Print/Download",
                theme: {
                    'stroke-width': 1,
                    stroke: 'silver',
                    fill: '#bada55',
                    r: 0,
                    states: {
                        hover: {
                            fill: '#bada55'
                        },
                        select: {
                            stroke: '#039',
                            fill: '#bada55'
                        }
                    }
                }
            }
        }
       
        });
       
    });
</script>

<!--<script type="text/javascript">
//Line Chart
$(function () {

var percentage=document.getElementById('percentage').value;
var examname=document.getElementById('examname').value;
//alert(percentage);alert(examname);

var percentage1 =percentage.split("~");
      var examname1 = examname.split("~");
      var exam=[],percent=[];
      for (var i=0;i<examname1.length;i++)
{
exam[i]=examname1[i];
percent[i]=percentage1[i];
}
//alert(exam);alert(percent);
        $('#line').highcharts({
            chart: {
                        backgroundColor: {
                linearGradient: [0, 0, 500, 500],
                stops: [
                    [0, 'rgb(255, 255, 255)'],
                    [1, 'rgb(200, 200, 255)']
                ]
            },
            borderColor: '#EBBA95',
            borderWidth: 2,
                type: 'line',
                margin: [ 50, 50, 100, 80]
            },
            title: {
                text: 'Exam Result...'
            },
            xAxis: {
                categories:exam,
                labels: {
                    rotation: -45,
                    align: 'right',
                    style: {
                   
                        fontSize: '13px',
                        fontFamily: 'Verdana, sans-serif'
                    }
                },
                 title: {
                    text: '<br/>Exam Names'
                }
            },
           
            yAxis: {
            gridLineColor: '#197F07',
            gridLineWidth: 2,
                min: 0,
                title: {
                    text: 'Marks ( percentage )'
                }
            },
            legend: {
                enabled: false
            },
            tooltip: {
                pointFormat: 'Marks: <b>{point.y:.1f} %</b>',
            },
            series: [{
                name: 'Percentage',
                data: JSON.parse("["+percent+"]"),
                dataLabels: {
                    enabled: true,
                    rotation: -90,
                    color: '#FFFFFF',
                    align: 'right',
                    x: 4,
                    y: 10,
                    style: {
                        fontSize: '13px',
                        fontFamily: 'Verdana, sans-serif',
                        textShadow: '0 0 3px black'
                    }
                }
            }],
            navigation: {
            buttonOptions: {
                text:"Print/Download",
                theme: {
                    'stroke-width': 1,
                    stroke: 'silver',
                    fill: '#bada55',
                    r: 0,
                    states: {
                        hover: {
                            fill: '#bada55'
                        },
                        select: {
                            stroke: '#039',
                            fill: '#bada55'
                        }
                    }
                }
            }
        }
       
        });
       
    });
</script> -->
</head>
<body>

<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<!-- <script src="chart/highcharts.js"></script>
<script src="chart/exporting.js"></script> -->
 
   <input type="hidden" id="percentage" name="percentage" value="56,70,80 "/>
    <input type="hidden" id="examname" name="examname" value="maths,social,hindi "/>
   
<div id="container" style="min-width: 500px; height: 400px; margin: 0 auto;" ></div>
<div id="line" style="min-width: 500px; height: 400px; margin: 0 auto;" ></div>
<br/>
<!-- <div id="line" style="min-width: 500px; height: 400px; margin: 0 auto;" ></div>
<br/> -->

<br/>
 


</body>
</html>

Bar graph charts code for getting reports by line charts


<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<script type="text/javascript">
//Line Chart
$(function () {

var percentage=document.getElementById('percentage').value;
var examname=document.getElementById('examname').value;
//alert(percentage);alert(examname);

var percentage1 =percentage.split("~");
      var examname1 = examname.split("~");
      var exam=[],percent=[];
      for (var i=0;i<examname1.length;i++)
{
exam[i]=examname1[i];
percent[i]=percentage1[i];
}
//alert(exam);alert(percent);
        $('#line').highcharts({
            chart: {
                        backgroundColor: {
                linearGradient: [0, 0, 500, 500],
                stops: [
                    [0, 'rgb(255, 255, 255)'],
                    [1, 'rgb(200, 200, 255)']
                ]
            },
            borderColor: '#EBBA95',
            borderWidth: 2,
                type: 'line',
                margin: [ 50, 50, 100, 80]
            },
            title: {
                text: 'Exam Result...'
            },
            xAxis: {
                categories:exam,
                labels: {
                    rotation: -45,
                    align: 'right',
                    style: {
                   
                        fontSize: '13px',
                        fontFamily: 'Verdana, sans-serif'
                    }
                },
                 title: {
                    text: '<br/>Exam Names'
                }
            },
           
            yAxis: {
            gridLineColor: '#197F07',
            gridLineWidth: 2,
                min: 0,
                title: {
                    text: 'Marks ( percentage )'
                }
            },
            legend: {
                enabled: false
            },
            tooltip: {
                pointFormat: 'Marks: <b>{point.y:.1f} %</b>',
            },
            series: [{
                name: 'Percentage',
                data: JSON.parse("["+percent+"]"),
                dataLabels: {
                    enabled: true,
                    rotation: -90,
                    color: '#FFFFFF',
                    align: 'right',
                    x: 4,
                    y: 10,
                    style: {
                        fontSize: '13px',
                        fontFamily: 'Verdana, sans-serif',
                        textShadow: '0 0 3px black'
                    }
                }
            }],
            navigation: {
            buttonOptions: {
                text:"Print/Download",
                theme: {
                    'stroke-width': 1,
                    stroke: 'silver',
                    fill: '#bada55',
                    r: 0,
                    states: {
                        hover: {
                            fill: '#bada55'
                        },
                        select: {
                            stroke: '#039',
                            fill: '#bada55'
                        }
                    }
                }
            }
        }
       
        });
       
    });
</script>
</head>
<body>

<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<!-- <script src="chart/highcharts.js"></script>
<script src="chart/exporting.js"></script> -->
 
   <input type="hidden" id="percentage" name="percentage" value="56,70,80 "/>
    <input type="hidden" id="examname" name="examname" value="maths,social,hindi "/>
   
<div id="container" style="min-width: 500px; height: 400px; margin: 0 auto;" ></div>
<div id="line" style="min-width: 500px; height: 400px; margin: 0 auto;" ></div>
<br/>
<!-- <div id="line" style="min-width: 500px; height: 400px; margin: 0 auto;" ></div>
<br/> -->

<br/>
 


</body>
</html>

Monday, 9 June 2014

Sample code for pagination using javascript

<!DOCTYPE html>

<html lang="en" class="no-js">
<head>
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/css/principalreport2.css" />
<link rel="stylesheet" type="text/css"
href="<%=request.getContextPath()%>/css/bootstrap.min.css" />

<style type="text/css">
td {
background-color: #ffffff;g
}

.tdbox {
padding: 3px;
}

.submit {
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #ededed
), color-stop(1, #dfdfdf) );
text-indent: -3px;
display: inline-block;
color: #303030;
font-family: Trebuchet MS;
font-size: 15px;
font-weight: normal;
font-style: normal;
height: 39px;
line-height: 27px;
width: 78px;
}
.container>header {
color: #000000;
}

.rightcell {
padding: 7px 10px 7px 23px;
}

input[type="checkbox"] {
width: inherit;
}

.modal-body {
height: 500px;
overflow-y: scroll;
}
</style>
<script>

function Check(chk) {
if (document.myform.Check_ctr.checked == true) {
for (i = 0; i < chk.length; i++)
chk[i].checked = true;
} else {
for (i = 0; i < chk.length; i++)
chk[i].checked = false;
}
}

function createPopup(accno)
{  
alert("accno==>"+accno);
var url = "<%=request.getContextPath()%>/createPopupLib.action?accno="+accno;
if (window.XMLHttpRequest)
  {  // Non-IE browsers
req = new XMLHttpRequest();
    req.onreadystatechange = showdata;  
    req.open("POST", url, true); //was get    
     req.send(null);
   }
    else if (window.ActiveXObject)
     { // IE
         req = new ActiveXObject("Microsoft.XMLHTTP");
          if (req)
          {
         req.onreadystatechange = showdata;
         req.open("POST", url, true);
          req.send();
  }  
  }
}
function showdata()
{
      if (req.readyState == 4)
       {
     
            if (req.status == 200)
            {
              document.getElementById("popup").innerHTML=req.responseText;    
             }
        }  
}

</script>
<script>/*
function download(val)
{
var type=val;
$("#output").html(type+type);
    str='downloadActionSZ.action?type='+type;
location=str;
}
*/</script>
</head>
  <body>
  <form name="deletedata" action="" >
   
     <div class="container">
    <header>
           
 
   </div>
</form>


<style type="text/css">

.pg-normal {
color: #000000;
font-size: 15px;
cursor: pointer;
background: #D0B389;
padding: 2px 4px 2px 4px;
}

.pg-selected {
color: #fff;
font-size: 15px;
background: #000000;

padding: 2px 4px 2px 4px;
}

table.yui {
font-family:arial;
border-collapse:collapse;
border: solid 3px #7f7f7f;
font-size:small;
}

table.yui td {
padding: 5px;
border-right: solid 1px #7f7f7f;
}

table.yui .even {
background-color: #EEE8AC;
}

table.yui .odd {
background-color: #F9FAD0;
}

table.yui th {
border: 1px solid #7f7f7f;
padding: 5px;
height: auto;
background: #D0B389;
}

table.yui th a {
text-decoration: none;
text-align: center;
padding-right: 20px;
font-weight:bold;
white-space:nowrap;
}

table.yui tfoot td {
border-top: 1px solid #7f7f7f;
background-color:#E1ECF9;
}

table.yui thead td {
vertical-align:middle;
background-color:#E1ECF9;
border:none;
}

table.yui thead .tableHeader {
font-size:larger;
font-weight:bold;
}

table.yui thead .filter {
text-align:right;
}

table.yui tfoot {
background-color:#E1ECF9;
text-align:center;
}

table.yui .tablesorterPager {
padding: 10px 0 10px 0;
}

table.yui .tablesorterPager span {
padding: 0 5px 0 5px;
}

table.yui .tablesorterPager input.prev {
width: auto;
margin-right: 10px;
}

table.yui .tablesorterPager input.next {
width: auto;
margin-left: 10px;
}

table.yui .pagedisplay {
font-size:10pt;
width: 30px;
border: 0px;
background-color: #E1ECF9;
text-align:center;
vertical-align:top;
}
</style>
<script type="text/javascript">

function Pager(tableName, itemsPerPage) {

this.tableName = tableName;

this.itemsPerPage = itemsPerPage;

this.currentPage = 1;

this.pages = 0;

this.inited = false;

this.showRecords = function(from, to) {

var rows = document.getElementById(tableName).rows;

// i starts from 1 to skip table header row

for (var i = 1; i < rows.length; i++) {

if (i < from || i > to)

rows[i].style.display = 'none';

else

rows[i].style.display = '';

}

}

this.showPage = function(pageNumber) {

if (! this.inited) {

alert("not inited");

return;

}

var oldPageAnchor = document.getElementById('pg'+this.currentPage);

oldPageAnchor.className = 'pg-normal';

this.currentPage = pageNumber;

var newPageAnchor = document.getElementById('pg'+this.currentPage);

newPageAnchor.className = 'pg-selected';

var from = (pageNumber - 1) * itemsPerPage + 1;

var to = from + itemsPerPage - 1;

this.showRecords(from, to);

}

this.prev = function() {

if (this.currentPage > 1)

this.showPage(this.currentPage - 1);

}

this.next = function() {

if (this.currentPage < this.pages) {

this.showPage(this.currentPage + 1);

}

}

this.init = function() {

var rows = document.getElementById(tableName).rows;

var records = (rows.length - 1);

this.pages = Math.ceil(records / itemsPerPage);

this.inited = true;

}

this.showPageNav = function(pagerName, positionId) {

if (! this.inited) {

alert("not inited");

return;

}

var element = document.getElementById(positionId);

var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> « Prev </span> ';

for (var page = 1; page <= this.pages; page++)

pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';

pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next »</span>';

element.innerHTML = pagerHtml;

}

}

</script>
</head>
<body>


<table id="tablepaging" class="yui" align="center">
<thead>


<tr>
<th>SNO</th>
<th>Accession Number</th>
<th>Record Title</th>
<th>Author/Authors</th>
<th>Publisher</th>
<th>Issued Date</th>


</tr>
</thead>
<tbody>

<tr class="even">
<td>Student10 </td>
<td>Languages </td>
<td>M </td>
<td>80 </td>
<td>70 </td>
<td>75 </td>

</tr>

<tr class="odd">
<td>Student11 </td>
<td>Languages </td>
<td>M </td>
<td>80 </td>
<td>70 </td>
<td>75 </td>

</tr>
<tr class="even">
<td>Student12 </td>
<td>Languages </td>
<td>M </td>
<td>80 </td>
<td>70 </td>
<td>75 </td>
</tr>

<tr class="odd">
<td>Student13 </td>
<td>Languages </td>
<td>M </td>
<td>80 </td>
<td>70 </td>
<td>75 </td>
</tr>
<tr class="even">
<td>Student14 </td>
<td>Languages </td>
<td>M </td>
<td>80 </td>
<td>70 </td>
<td>75 </td>
</tr>
<tr class="odd">
<td>Student15 </td>
<td>Languages </td>
<td>M </td>
<td>80 </td>
<td>70 </td>
<td>75 </td>
</tr>
<tr class="even">
<td>Student16 </td>
<td>Languages </td>
<td>M </td>
<td>80 </td>
<td>70 </td>
<td>75 </td>
</tr>

</tbody>
</table>
<div id="pageNavPosition" style="padding-top: 20px" align="center">
</div>
 
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="<%=request.getContextPath() %>/js/bootstrap.js"></script>
<script type="text/javascript">
var pager = new Pager('tablepaging', 5);
pager.init();
pager.showPageNav('pager', 'pageNavPosition');
pager.showPage(1);
</script>
 


<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
   <form name="insertform" action="Lib.action" method="post">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
       
      </div>
      <div class="modal-body"  style="height:auto;">
<span id="popup"></span>
      </div>
     
    </div><!-- /.modal-content -->
    </form>
   
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

</body>
</html>

Friday, 6 June 2014

javaScript validation for when we don't want to select both values and when we want to select both values

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - checking non-empty</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
<script>
function required()
{
var empt = document.forms["form1"]["text1"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
else  
{
alert('Code has accepted : you can try another');
return true;  
}
}
</script>        
 </head>
<body>
<div class="mail">
<h2>Input your Name and Submit</h2>
<form name="form1" action="#" onsubmit="required()">
<ul>
<li><input type='text' name ='text1'/></li>
<li class="rq">*Required Field</li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</div>
<script src="non-empty.js"></script>
</body>
</html>

javascript validation for when we don't want to select both values and when we want to select both

<script>
function fun(){
var empt = document.forms["getCondDetails"]["formuserid"].value;
var Classname = document.forms["getCondDetails"]["Classname"].value;
  if (empt == "" && Classname == "")
  {
  alert("Please input a Values");
  return false;
  }
  if (empt != "" && Classname != "")
  {
  alert("Please don't submit both ID number and remaining fields");
  return false;
  }

 return true;

}
</script>