Showing posts with label Java Script. Show all posts
Showing posts with label Java Script. Show all posts

Tuesday, December 3, 2013

jQuery fast review

Here I have provided some jQuery properties which will give you overview & to quick learn.

While writing jQuery we need to remember two things i.e  
      #"Find element" .. and
      #"do something to it"..
Find element : find a element by selector..
i.e. $("")  --- selector
jQuery selectors are used to "find" (or select) HTML elements based on their id, classes, types, attributes, values of attributes.

You can select a element by using 
    "element id" using "#"                     -- eg: $("#divid")
    "class attribute" using "." (dot)        -- eg: $(".classname")
    "element tag"  using tag name         -- eg: $("table"), $("div"),..

Examples:
$("#contentid")  -- get element with id "contentid" .
$("li:first")          -- get first list item.
$("tr:odd")         -- get odd numbered table rows
$(this).hide()      -- hides the current element.
$("p").hide()      -- hides all <p> elements.
$(".test").hide()  -- hides all elements with class="test".
$("#test").hide() -- hides the element with id="test".

Properties :
Here are some of properties which are most using..

Hide all div's with jQuery :
$("div").hide( );

You can also find element by string selectors together
$("#myid, .myclass, table")

Add Class:
$("div").addclass("myclass");
here selector find element div and add class attribute "myclass" to it.

jQuery API
Chain method
$("div").addclass("myclass").fadeout();

•Moving Elements:
append(), appendTo(), before(), after(),
•Attributes
css(), attr(), html(), val(), addClass()
•Traversing
find(), is(), prevAll(), next(), hasClass()
•Events
bind(), trigger(), unbind(), live(), click()
•Ajax
get(), getJSON(), post(), ajax(), load()
•Effects
show(), fadeOut(), toggle(), animate()

...post incomplete, updating

Monday, December 2, 2013

Float div position to top when you scroll

In the below code I have explained about Maintaining div tag at top of the screen when scrolling..

IF my current position is greater or equal to the “sticker” position, give the sticker div a class of “stick”.  This changes the CSS of the div to have a FIXED position as long as the viewport is lower than the position of the sticker.





HTML - Take a div tag which contain the data which you want to float.

<div id="sticker">
    ...start scrolling..
   //Add your Code block here...
</div>

CSS 
Styles applied to div#sticker and the class “.stick
"stick" class is most important, which maintain position when you scroll.

div#sticker {
    padding:20px;
    margin:20px 0;
    background:#AAA;
    width:190px;
}
.stick {
    position:fixed;
    top:0px;

}


jQuery – Calculates the position of the sticker div and makes its position fixed if the page has scrolled that far

$(document).ready(function() {
    var s = $("#sticker");
    var pos = s.position();                    
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();
        s.html("Distance from top:" + pos.top + "<br />Scroll position: " + windowpos);
        if (windowpos >= pos.top) {
            s.addClass("stick");
        } else {
            s.removeClass("stick"); 
        }

    });

Tuesday, September 24, 2013

Dynamically Enable or Disable Required Field Validator


To enable or disable the required field validator control based on any selection
Enable or Disable ASP.Net Validation on client side

//Syntax:
ValidatorEnable(ValidatorContronName,Boolean);

//Explanation:
ValidatorContronName - This is ClientID of the Validation control.
Boolean - true(Enable) / false(Disable)

//Example:
rfvOther: is a Required Field Validator
ValidatorEnable(document.getElementById('<%=rfvOther.ClientID%>'), false);


Explonation#2:
'ValidatorEnable' or 'ValidatorUpdateDisplay' will immediately validate the associated control and show any validation messages. If this is not wanted because you just want to toggle the enabled/disabled switch but wait until form submission to validate, then the 2nd method of calling enabled on the object is the preferred method. If you do want immediate validation, then this can be done in a single line of code passing in the ID of the RequiredFieldValidator as displayed below:
ValidatorEnable($get('<%=RequiredFieldValidator1.ClientID %>'), true);
However, if you want only to enable/disable the validator, use the code below and do not make any additional calls to the built in JS functions. The error from previous posts states to set the .enable property yet there is no such thing. You must set the .enabled property on the server control. The code below shows this:
var validator = $get('<%=RequiredFieldValidator1.ClientID %>');
validator.enabled = true;

Monday, July 22, 2013

Check if Function Exists Before Calling

When using scripts that are shared between different areas of a site, there may be cases where a function is called that doesn't exist. 
you can just check if the function exists before calling it to avoid the error:

Java Script :
if (typeof yourFunctionName == 'function') { yourFunctionName(); }else{ alert('Check yourFunctionName!'); }

Jquery:
Also could be:
$.isFunction(yourFunctionName)&&yourFunctionName()

or if you are sure that if its exists than its a function:
yourFunctionName&&yourFunctionName()

Monday, July 2, 2012

How to set selectedIndex of select element using JavaScript



Example:

<input id="AnimalToFind" type="text" />
<select id="Animals">
    <option value="0">Chicken</option>
    <option value="1">Crocodile</option>
    <option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />
<script type="text/javascript">
    function SelectAnimal()
    {
        //Set selected option of Animals based on AnimalToFind value...
    }
 </script>
function SelectAnimal() {
    var sel = document.getElementById('Animals');
    var val = document.getElementById('AnimalToFind').value;
    for(var i = 0, j = sel.options.length; i < j; ++i) {
        if(sel.options[i].innerHTML === val) {
           sel.selectedIndex = i;
           break;
        }
    }
}

Friday, June 15, 2012

Number To Word JavaScript


    <script>
        function Convert(rupeeval) {

            var rVal = rupeeval;
            rVal = Math.floor(rVal);
            var rup = new String(rVal);
            rupRev = rup.split("");
            actualNumber = rupRev.reverse();

            if (Number(rVal) >= 0) {

            }
            else {
                alert('Number cannot be converted');
                return false;
            }
            if (Number(rVal) == 0) {
                document.getElementById('wordValue').innerHTML = rup + '' + 'Rupees Zero Only';
                return false;
            }
            if (actualNumber.length > 9) {
                alert('the Number is too big to covertes');
                return false;
            }

            var numWords = ["Zero", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine"];
            var numPlace = ['Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen'];
            var tPlace = ['dummy', ' Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'];

            var numWordsLength = rupRev.length;
            var totalWords = "";
            var numtoWords = new Array();
            var finalWord = "";
            j = 0;
            for (i = 0; i < numWordsLength; i++) {
                switch (i) {
                    case 0:
                        if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                            numtoWords[j] = '';
                        }
                        else {
                            numtoWords[j] = numWords[actualNumber[i]];
                        }
                        numtoWords[j] = numtoWords[j] + ' Only';
                        break;
                    case 1:
                        CTen();
                        break;
                    case 2:
                        if (actualNumber[i] == 0) {
                            numtoWords[j] = '';
                        }
                        else if (actualNumber[i - 1] != 0 && actualNumber[i - 2] != 0) {
                            numtoWords[j] = numWords[actualNumber[i]] + ' Hundred and';
                        }
                        else {
                            numtoWords[j] = numWords[actualNumber[i]] + ' Hundred';
                        }
                        break;
                    case 3:
                        if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                            numtoWords[j] = '';
                        }
                        else {
                            numtoWords[j] = numWords[actualNumber[i]];
                        }
                        if (actualNumber[i + 1] != 0 || actualNumber[i] > 0) {
                            numtoWords[j] = numtoWords[j] + " Thousand";
                        }
                        break;
                    case 4:
                        CTen();
                        break;
                    case 5:
                        if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                            numtoWords[j] = '';
                        }
                        else {
                            numtoWords[j] = numWords[actualNumber[i]];
                        }
                        if (actualNumber[i + 1] != 0 || actualNumber[i] > 0) {
                            numtoWords[j] = numtoWords[j] + " Lakh";
                        }
                        break;
                    case 6:
                        CTen();
                        break;
                    case 7:
                        if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                            numtoWords[j] = '';
                        }
                        else {
                            numtoWords[j] = numWords[actualNumber[i]];
                        }
                        numtoWords[j] = numtoWords[j] + " Crore";
                        break;
                    case 8:
                        CTen();
                        break;
                    default:
                        break;
                }
                j++;
            }

            function CTen() {
                if (actualNumber[i] == 0) {
                    numtoWords[j] = '';
                }
                else if (actualNumber[i] == 1) {
                    numtoWords[j] = numPlace[actualNumber[i - 1]];
                }
                else {
                    numtoWords[j] = tPlace[actualNumber[i]];
                }
            }
            numtoWords.reverse();
            for (i = 0; i < numtoWords.length; i++) {
                finalWord += numtoWords[i];
            }

        }

</script>

Collection of Javascript validations



Text Box Empty Validation:-
[code]
function TextboxEmptyValidation()
{
var txt=document.getElementById("TextBox1");
if(txt.value=="")
{
alert("Textbox cannot be blank");
txt.focus();
return false;
}
}
You can call above function like this

<asp:TextBox ID="TextBox1" onblur="return TextboxEmptyValidation()" runat="server"></asp:TextBox>
[/code]

if you want to enter only number for particular textbox means,you will call the below function in textbox onkeypress event.

Text Box Enter only Numbers:-
[code]
function valNumeric(evt)
{

var charCode;
charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode <= 48 && charCode >= 57 || charCode== 8 || charCode == 118 || charCode == 120 || charCode == 99 )
{
return true;
}
else
{
return false;
}
}

You can call above function like this

<asp:TextBox ID="TextBox2" onkeypress="return valNumeric(event)" runat="server"></asp:TextBox>

[/code]

if user does not select value from dropdownlist means,we will show a alert message throguh java script.
check the below code for java script dropdownlist empty validation.

Dropdownlist empty validation

[code]
function DropdownlistEmptyValidation()
{
var dropdown=document.getElementById("DropDownList1");
if(dropdown.value=="-1")
{
alert("dropdownlist cannot be blank");
dropdown.focus();
return false;
}
}
You can call the above function like this

<asp:DropDownList ID="DropDownList1" onblur="return DropdownlistEmptyValidation()" runat="server" AutoPostBack="True">
<asp:ListItem Value="-1">---Select--</asp:ListItem>
<asp:ListItem>Item1</asp:ListItem>
<asp:ListItem>Item2</asp:ListItem>
<asp:ListItem>Item3</asp:ListItem>
</asp:DropDownList>


[/code]

if you want to enter only char for particular textbox means,you will call the below function in textbox onkeypress event.

Enter only char
[code]
function valAlpha(evt)
{

var charCode;
charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode <= 97 && charCode >= 122 || charCode <= 65 && charCode >= 90 || charCode==8)
{
return true;
}
else
{
return false;
}
}
You can call the above function like this

<asp:TextBox ID="TextBox3" onkeypress="return valAlpha(event)" runat="server"></asp:TextBox>
[/code]
if you want to check given website is valid or not,using javascript.take the below code to check valid or not

WebsiteValidation
[code]
function WebsiteValidation(ctrName)
{
var strURL=document.getElementById(ctrName).value;
if(strURL!='')
{
var tomatch= /www\.[A-Za-z0-9\.-]{2,}\.[A-Za-z]{2}/
if (tomatch.test(strURL))
{
var cnt1 = strURL.length - 1;
var cnt2 = strURL.lastIndexOf(".");
if(cnt1 == cnt2 )
{
alert("Enter valid Website");

return false;
}
return true;
}
else
{ alert("Enter valid Website");
return false;
}
}
}

You can call the above function like this

<asp:TextBox ID="TextBox4" onblur="return WebsiteValidation(this.id)" runat="server"></asp:TextBox>
[/code]

Tuesday, June 12, 2012

Working with JQuery Templates



The JQuery templates feature is available in the file jquery.tmpl.min.js, which can be downloaded from here. It works well with JQuery version 1.4.4 or greater. The method that does this template data binding in JQuery is .tmpl().

Two Different Ways to Render a JQuery Template

A JQuery template can be rendered in two different ways. You can inject the child HTML tags along with the data expression to the .tmpl() method as a string. Below is the syntax.
  1. $.tmpl("<tr><td>${Column1}</td><td>${Column2}</td></tr>", dataObject).appendTo("#yourHtmlContainer");
You can also define a reusable template and later use it to bind the data to an HTML container control. Below is the syntax.
  1. $("#yourTemplate").tmpl(dataObject).appendTo("yourContainerControl");

Binding the JSON Data Using a JQuery Template - Example

In this section I will take you through creating a sample web page implementing a JQuery template. Create an empty Asp.Net web application and add an HTML page named JQueryTemplateSample.Htm. Add the reference to the JQuery and JQuery template script files onto the web page. In this web page I will bind the list of employee data on to an HTML table control using a pre-defined JQuery template. Below is the code.
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>JUquery Template sample</title>
  5.     <script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
  6.     <script src="Scripts/jquery.tmpl.min.js" type="text/javascript"></script>
  7.     <script type="text/javascript">
  8.         $(document).ready(function () {
  9.             var employeeData = [
  10.                 { FirstName: "Rob", LastName: "Mathews", Age: 26 },
  11.                 { FirstName: "Richie", LastName: "Richards", Age: 32 },
  12.                 { FirstName: "Shawn", LastName: "Clarke", Age: 53 },
  13.                 { FirstName: "Dave", LastName: "Canterburry", Age: 42 }
  14.             ];
  15.  
  16.             $("#MyTemplate").tmpl(employeeData).appendTo("#employeeContainer");
  17.         });
  18.     </script>
  19.     <script id="MyTemplate" type="text/x-jquery-tmpl">
  20.         <tr>
  21.             <td>${FirstName}</td>
  22.             <td>${LastName}</td>
  23.             <td>${Age}</td>
  24.         </tr>
  25.     </script>
  26. </head>
  27. <body>
  28.     <table>
  29.         <thead>
  30.             <th>
  31.                 First Name
  32.             </th>
  33.             <th>
  34.                 Last Name
  35.             </th>
  36.             <th>
  37.                 Age
  38.             </th>
  39.         </thead>
  40.         <tbody id="employeeContainer">
  41.         </tbody>
  42.     </table>
  43. </body>
  44. </html>
I have defined a static JSON employee data having the fields FirstName, LastName and Age. The template should be defined under the script tag with type as “text/x-jquery-tmpl”. This is a special type that allows JQuery to understand that it is a template definition. Run the web page and Fig 1.0 shows the data bound to the table.
Fig 1.0: JUquery Template Sample
Fig 1.0: JUquery Template Sample
Inside the template definition you can also make use of the ${{each}} tag to loop through the data and ${{if}} tag to implement an if/else condition. Below is the sample code where I can show the seniority based on the age of the employee using ${{if}}.
  1. <script id="MyTemplate" type="text/x-jquery-tmpl">
  2.         <tr>
  3.             <td>${FirstName}</td>
  4.             <td>${LastName}</td>
  5.             <td>${Age}</td>
  6.             <td>{{if Age > 40}}
  7.                     Yes
  8.                 {{else}}
  9.                     No
  10.                 {{/if}}
  11.             </td>
  12.         </tr>
  13. </script>
Now say you want the FirstName and LastName to be concatenated and shown as a single column EmployeeName then you can define a javascript function to concatenate two strings and call the function inside the template as shown below.
  1. <script type="text/javascript">
  2.         function GetName(firstName, lastName) {
  3.             return firstName + " " + lastName;
  4.         }
  5. </script>
  6. <script id="MyTemplate" type="text/x-jquery-tmpl">
  7.         <tr>
  8.             <td>${GetName(FirstName, LastName)}</td>
  9.             <td>${Age}</td>
  10.             <td>{{if Age > 40}}
  11.                     Yes
  12.                 {{else}}
  13.                     No
  14.                 {{/if}}
  15.             </td>
  16.         </tr>
  17. </script>