Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Sunday, July 22, 2012

How to show Modal Dialog Box with JQueryUI API in Asp.net Web Form

I used JQuery a lot thesedays for user interactive web pages and then I start using JQueryUI for Dialog box in web form. I realize that It is simpler and more effective than I expected. This post explain you how to create Modal Dialog with JQueryUI in asp.net web form.
A dialog is a floating window that contains a title bar and a content area. The dialog window can be moved, resized and closed with the 'x' icon by default.
If the content length exceeds the maximum height, a scrollbar will automatically appear.

JQueryui Dialog Box in ASP.Net Web Form

First you need to download the JQuery UI API here and copy them to your project folder. After that, copy and paste the following code to <head> tag.
<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript">
    $(function () {
        // Dialog
        $('#dialog').dialog({
            autoOpen: false,
            width: 500,
            closeOnEscape: true,
            resizable: false,
            draggable: true,
            modal: true,
            title: "Customer Details"
        });

        // Dialog Link
        $('#btnEditText').click(function () {
            $('#dialog').dialog('open');
            $('#dialog').parent().appendTo($('form:first'));
            return false;
        });

        $('#editBox_Cancel').click(function () {
            $('#dialog').dialog('close');
            return false;
        });
    });
</script>
Create the following control in <form> tag. There are tow sessions (two div) for displaying customer information. One is main content and other is for editing.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
    <!--Using Partial Rendering to Update the Customer View -->
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table>
                <tr>
                    <td>
                        <b>Customer ID:</b>
                    </td>
                    <td>
                        <asp:Label runat="server" ID="lblCustomerID" Text="C00001" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Company Name:</b>
                    </td>
                    <td>
                        <asp:Label runat="server" ID="lblCompanyName" Text="Eastern Connection" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Contact Name:</b>
                    </td>
                    <td>
                        <asp:Label runat="server" ID="lblContactName" Text="Ann Devon" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Country:</b>
                    </td>
                    <td>
                        <asp:Label runat="server" ID="lblCountry" Text="Germany" />
                    </td>
                </tr>
            </table>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="editBox_OK" />
        </Triggers>
    </asp:UpdatePanel>
    <asp:Button runat="server" ID="btnEditText" Text="Edit text" />
</div>
<div id="dialog">
    <!-- Dialog box:: Edit customer info -->
    <asp:UpdatePanel runat="server" ID="ModalPanel1" RenderMode="Inline" UpdateMode="Conditional">
        <ContentTemplate>
            <table>
                <tr>
                    <td>
                        <b>Customer ID:</b>
                    </td>
                    <td>
                        <asp:Label runat="server" ID="editCustomerID" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Company Name:</b>
                    </td>
                    <td>
                        <asp:TextBox runat="server" ID="editTxtCompanyName" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Contact Name:</b>
                    </td>
                    <td>
                        <asp:TextBox runat="server" ID="editTxtContactName" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Country:</b>
                    </td>
                    <td>
                        <asp:TextBox runat="server" ID="editTxtCountry" />
                    </td>
                </tr>
            </table>
            <hr />
            <asp:Button ID="btnApply" runat="server" Text="Apply" OnClick="btnApply_Click" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:Button ID="editBox_OK" runat="server" Text="OK" OnClick="editBox_OK_Click" />
    <asp:Button ID="editBox_Cancel" runat="server" Text="Cancel" />
</div>
In code-behind, the coding is as below.
protected void InitDialog()
{
    editCustomerID.Text = lblCustomerID.Text;
    editTxtCompanyName.Text = lblCompanyName.Text;
    editTxtContactName.Text = lblContactName.Text;
    editTxtCountry.Text = lblCountry.Text;
    SetFocus("editTxtCompanyName");
}
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        InitDialog();
    }
}
protected void editBox_OK_Click(object sender, EventArgs e)
{
    // Save to the database
    // Refresh the UI
    lblCompanyName.Text = editTxtCompanyName.Text;
    lblContactName.Text = editTxtContactName.Text;
    lblCountry.Text = editTxtCountry.Text;
}
protected void btnApply_Click(object sender, EventArgs e)
{
    if (editTxtCountry.Text == "Germany")
        editTxtCountry.Text = "Cuba";
    else
        editTxtCountry.Text = "USA";
}
The jQuery UI API provides us simple and advance effects that you can use to create highly interactive web applications. Like other jQuery UI effects, jQuery UI Dialog is easy to use. Using it on the right way to help it be more flexible and scalability. You can see other post(How to show Modal Dialog Box with ASP.Net Ajax) I wrote before. Thank.

More Details

Other Nice Post

Monday, June 18, 2012

Simple jQuery Confirm and Alert Dialogs

These days, JQuery is getting more powerful and more useful for rich interactive web application. For myself, I used a lot of JQuery for web interface and ajax pattern. Here, I show you the simple and easy way to use the beautiful jquery Confirm and Alert popup as below.

JQuery confirm popup
First, you need to download the jquery library and resource here (it inclueds images, css and js file.).
Put the following code to <head> tag.
<script src="jquery.alerts.js" type="text/javascript"></script>
<link href="jquery.alerts.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
 function ConfirmPopup() {
   jConfirm('Can you confirm to leave page?', 'Confirmation Message', function (r) {
     if (r) {
       jAlert('Please visit again.', 'Alert Message' , function (r) {
         window.location = 'http://www.aspmemo.net';
       });
     }
   });
}
Create the sever button control like this.
<asp:button id="Button1" onclick="Button1_Click" runat="server" text="Show Confirm">
In that button click event, we register the created javascript function to call.
protected void Button1_Click(object sender, EventArgs e)
{
 Page.ClientScript.RegisterStartupScript(this.GetType(), "popupScript", "ConfirmPopup()", true);
}
That's it. When you clicks the button, it show Confirm popup and then click on Ok button, it show Alert pop and click on OK again, it redirects to one url.

More details bout this JQuery Plugin

Saturday, May 12, 2012

Multiple selecting the table cell using JQuery

A few year ago, it was challenging a lot for web developer because of intensive user requirement such as complex interactive user interface and design in web page. Nowadays, it can be solved it out easily due to JQuery that is designed to change the way that you write JavaScript. This example show you how to select multiple cells in table.

Multiple Selecting cells in table

Saturday, March 24, 2012

Gridview rows blink using JQuery in asp.net

When I'm developing an application with .NET platform, I have a case that is a Gridview row blinking depend on the some column data every one second. I solved it out using JQuery and it is also a simple way by applying "setTimeout" javascript function as below.

Gridview Row Blinking
Gridview Row Blinking
Put the following style sheet to <head> tag.
<style type="text/css">     .bgRow     {         background-color: Green;     }     .norRow     {         background-color: Silver;     } </style>
 Add the following scripts to <head> tag.
<script src="yourUrl/jquery-1.4.1.min.js" type="text/javascript"></script> //it need for JQuery <script type="text/javascript">     function setBG(gridId) {         var id = "#" + gridId;         $(id).find("tr").each(function () {             var css = $(this).attr("class");             if (css != null && css == "bgRow")                 $(this).addClass("norRow").removeClass("bgRow");             else if (css != null && css == "norRow")                 $(this).addClass("bgRow").removeClass("norRow");         });         setTimeout("setBG('" + gridId + "')", 1000); //1000 is equal to one second and call function every one second.     } </script>
Create a Gridview as below. I used "Northwind" db and "Suppliers" table. 
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
    AllowPaging="True" AlternatingRowStyle-Wrap="True" EmptyDataText="There is no data."
    OnRowDataBound="GridView1_RowDataBound" 
    onpageindexchanging="GridView1_PageIndexChanging">
    <Columns>
        <asp:BoundField HeaderText="Supplier ID" DataField="SupplierID" />
        <asp:BoundField HeaderText="Company Name" DataField="CompanyName" />
        <asp:BoundField HeaderText="Address" DataField="Address" />
        <asp:BoundField HeaderText="Country" DataField="Country" />
    </Columns>
</asp:GridView>
Add the below code snippet to code-behind.
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        if (!Page.IsPostBack)
        {
            using (var context = new NorthwindEntities())
            {
                //Data binding here. I used EF.                 var suppliers = context.Suppliers.ToList();                 GridView1.DataSource = suppliers;                 GridView1.DataBind();             }            }
        //Register javascript and call "setBG" function.         ClientScript.RegisterStartupScript(GetType(), "BG", "setBG('" + GridView1.ClientID + "')", true);     }     catch (Exception ex)     {             } } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {     if (e.Row.RowType == DataControlRowType.DataRow)     {         string country = DataBinder.Eval(e.Row.DataItem, "Country").ToString();         if(country == "USA")  //set the row background color on condition here.             e.Row.CssClass = "bgRow";     } } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) {
    //handle for page index here     GridView1.PageIndex = e.NewPageIndex;     using (var context = new NorthwindEntities())     {         var suppliers = context.Suppliers.ToList();         GridView1.DataSource = suppliers;         GridView1.DataBind();     } }
That's all what you have to do. You'll be glad you did.
Every row has blinking, when they have "Country" column is "USA".

Thursday, December 22, 2011

$(document).ready() vs pageLoad() vs Application.Init

jQuery’s $(document).ready()

    * Ideal for onetime initialization.
    * Optimization black magic; may run slightly earlier than pageLoad().
    * Does not re-attach functionality to elements affected by partial postbacks.

ASP.NET AJAX’s pageLoad()

    * Unsuitable for onetime initialization if used with UpdatePanels.
    * Slightly less optimized in some browsers, but consistent.
    * Perfect for re-attaching functionality to elements within UpdatePanels.

ASP.NET AJAX’s Application.Init

    * Useful for onetime initialization if only ASP.NET AJAX is available.
    * More work required to wire the event up.
    * Exposes you to the “sys is undefined” error if you aren’t careful. For this error, see this post
       http://www.aspmemo.net/2011/12/how-to-solve-sys-is-undefined-error.html


Original Post : http://encosia.com/document-ready-and-pageload-are-not-the-same/

What is jQuery?

jQuery is a library of JavaScript Functions.

jQuery is a lightweight "write less, do more" JavaScript library.

The jQuery library contains the following features:

    * HTML element selections
    * HTML element manipulation
    * CSS manipulation
    * HTML event functions
    * JavaScript Effects and animations
    * HTML DOM traversal and modification
    * AJAX
    * Utilities

More detail : http://www.w3schools.com/jquery/jquery_intro.asp

Tuesday, December 20, 2011

JQuery : Using events to take effect when the user interacts with the browser

For every onxxx event available, like onclick, onchange, onsubmit, there is a jQuery equivalent. Some other events, like ready and hover, are provided as convenient methods for certain tasks.

Here is CSS and script to put <head> tag.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<style type="text/css">
     .highlight { border: 5px dotted #eee;}
</style>
<script type="text/javascript">
    $(document).ready(function () {
        //go here the following example scripts
    });
</script>

Add the following to <body> tags.
<a name="top" href="#bottom">Go to bottom</a>
<form id="form">
    Form 1
    <input type="text" value="XXX"/>
</form>
<form>
    Form 2
    <input type="text" value="YYY"/>
</form>
<a id="reset" href="#">Reset!</a>
<br />
<a id="clickme" href="http://www.aspmemo.net">Click Me!</a>
<p>This is probably the most common mishap. The remedy is simple--yank! It's most easily done
with two people. One to restrain the bird and the <a href="#"> This is a link. Hover me to
highlight the parent paragraph.</a> other to pull the feather. Use pliers, or a hemostat. Tweezers won't
work on primaries.</p>
<p>This is probably the most common mishap. The remedy is simple--yank! It's most easily done
with two people. One to restrain the bird and the <a href="#"> This is a link. Hover me to
highlight the parent paragraph.</a> other to pull the feather. Use pliers, or a hemostat. Tweezers won't
work on primaries.</p>
<a name="bottom" href="#top">Go to top</a>

One task you often face is to call methods on DOM elements that are not covered by jQuery. Think of a form you would like to reset after you submitted it successfully via AJAX.

$(document).ready(function() {
   // use this to reset a single form
   $("#reset").click(function() {
     $("form")[0].reset();
   });
 });
This code selects the first form element and calls reset() on it. In case you had more than one form, you could also do this:

 $(document).ready(function() {
   // use this to reset several forms at once
   $("#reset").click(function() {
     $("form").each(function() {
       this.reset();
     });
   });
 });
This would select all forms within your document, iterate over them and call reset() for each. Note that in an .each() function, this refers to the actual element. Also note that, since the reset() function belongs to the form element and not to the jQuery object, we cannot simply call $("form").reset() to reset all the forms on the page.
The [expression] syntax is taken from XPath and can be used to filter by attributes. Maybe you want to select all anchors that have a name attribute:

$(document).ready(function() {
   $("a[name]").css("background", "#eee" );
 });
This adds a background color to all anchor elements with a name attribute.

More often than selecting anchors by name, you might need to select anchors by their "href" attribute. This can be a problem as browsers behave quite inconsistently when returning what they think the "href" value is. To match only a part of the value, we can use the contains select "*=" instead of an equals ("="):

 $(document).ready(function() {
   $("a[href*='aspmemo']").click(function() {
        alert('Bye JQuery!');
   });
 });
For all hovered anchor elements, the parent paragraph is searched and a class "highlight" added and removed. In addition, you can also select parent elements (also known as ancestors for those more familiar with XPath). Maybe you want to highlight the paragraph that is the parent of the link the user hovers. Try this:

 $(document).ready(function(){
   $("a").hover(function(){
     $(this).parents("p").addClass("highlight");
   },function(){
     $(this).parents("p").removeClass("highlight");
   });
 });
For all hovered anchor elements, the parent paragraph is searched and a class "highlight" added and removed.

Lets shop here. See you.

Useful link : http://www.w3schools.com/jquery/jquery_ref_events.asp

JQuery : Using selectors to get the specific elements

jQuery provides two approaches to select elements. The first uses a combination of CSS and XPath selectors passed as a string to the jQuery constructor (eg. $("div > ul a")). The second uses several methods of the jQuery object. Both approaches can be combined. Let's start here.

Here is CSS and script to put <head> tag.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<style type="text/css">
    .red { background-color: red;}
    .blue { color: blue;}
    .green { color: green; }
</style>
<script type="text/javascript">
    $(document).ready(function () {
        $("#orderedlist").addClass("red");
        $("#orderedlist > li").addClass("blue");
        $("#orderedlist li:last").hover(function () {
            $(this).addClass("green");
        }, function () {
            $(this).removeClass("green");
        });
    });                
</script>

Add the following to the <body>:
<ol id="orderedlist">
    <li>First element</li>
    <li>Second element</li>
    <li>Third element</li>
</ol>
   
To try some of these selectors, we select and modify the first ordered list in our example.
To get started, we want to select the list itself. The list has an ID "orderedlist". In classic JavaScript, you could select it by using document.getElementById("orderedlist"). With jQuery, we did it like this:

 $(document).ready(function() {
   $("#orderedlist").addClass("red");
 });

The example provides a stylesheet with a class "red" that simply adds a red background. Therefore, when you reload the page in your browser, you should see that the ordered list has a red background. I added some more classes to the child elements of this list as below.

 $(document).ready(function() {
   $("#orderedlist > li").addClass("blue");
 });

This selects all child lis of the element with the id orderedlist and adds the class "blue".
Now for something a little more sophisticated: We want to add and remove the class when the user hovers the li element, but only on the last element in the list. So, I inserted them to $(document).ready() like below:

   $("#orderedlist li:last").hover(function() {
     $(this).addClass("green");
   },function(){
     $(this).removeClass("green");
   });

There are many other selectors similar to CSS and XPath syntax.

Full post : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Find_me:_Using_selectors_and_events

Other useful link : http://www.w3schools.com/jquery/jquery_ref_selectors.asp

Monday, December 19, 2011

Hello jQuery / Getting Started with jQuery

We start with an empty html page or .aspx page.This page just loads the .js library (make sure the URL points to where you stored your copy of jquery).As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events as soon as the DOM is ready.
To do this, we register $(document).ready event for the document. Putting an alert into that function does not make much sense, as an alert does not require the DOM to be loaded. So lets try something a little more sophisticated: Show an alert when clicking a link.

Here is script.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
//otherwise, you can use built-in .js file while you use VS 2010.
<script type="text/javascript">
 $(document).ready(function() {
   $("a").click(function() {
     alert("Hello world!");
   });
 });
</script>

//Add the following to the <body>:
<a href="">Link</a>

This should show the alert as soon as you click on the link. Let's have a look at what we are doing: $("a") is a jQuery selector, in this case, it selects all a elements. $ itself is an alias for the jQuery "class", therefore $() constructs a new jQuery object. The click() function we call next is a method of the jQuery object. It binds a click event to all selected elements (in this case, a single anchor element) and executes the provided function when the event occurs.

This is similar to the following code:
<a href="" onclick="alert('Hello world')">Link</a>

The difference is quite obvious: We don't need to write an onclick for every single element. We have a clean separation of structure (HTML) and behavior (JS), just as we separate structure and presentation by using CSS.

Source : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Hello_jQuery

Sunday, December 18, 2011

How to create silde down FAQs using jQuery.

This example will show you how to use jQuery in order to generate easy-to-read and eye-pleasing FAQs, with a slide down effect. we are going to apply a “faq” class to the <dl> element so that it do not affect the other definition lists throughout the page. First of all we need to find and hide all the <dd> elements which are children of any <dl> element with the “faq” class. And then we need to add the toggle effect when a user clicks on a definition title so that when the user clicks on the <dt>, the script navigates the DOM to find the next element (which is going to be the relative <dd>), and it toggles it. You can set the motion’s speed to “slow”, “normal” or “fast”.
FAQs using JQuery

Here is built-in javascript file while you created web site with Visual Studio 2010. Put the below to <head>
tag.
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
Otherwise, you can use the following script reference.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Here is CSS in <head> tag.
<style type="text/css">
    .faq
    {
        margin: 30px;
        background: #d7e7ff;
        padding: 30px 50px 0 30px;
        border: 1px solid #92cdec;
    }
    .faq dt
    {
        font-weight: bold;
        padding: 3px 0 15px 0px;
        position: relative;
        cursor: pointer;
    }
    .faq dd
    {
        padding: 0 0 5px 0px;
        position: relative;
        color: #333;
    }
</style>

Here is javascript to add <head> tag.
<script type="text/javascript">
    $(document).ready(function () {
        $('.faq dd').hide();
        $('.faq dt').click(function () {
            $(this).next().slideToggle('normal');
        });
    });
</script>

Here is form tag.
<form id="form1" runat="server">
    <dl class="faq">
        <dt>Q.How can we check if all the validation control are valid and proper?</dt>
        <dd>A.Using the Page.IsValid () property you can check whether all the validation are done.</dd>
        <dt>Q.If client side validation is enabled in your Web page, does that mean server side code is not run.</dt>
        <dd>A.When client side validation is enabled server emit’s JavaScript code for the custom validators. However,
            note that does not mean that server side checks on custom validators do not execute. It does this redundant
            check two times, as some of the validators do not support client side scripting.
        </dd>
        <dt>Q.How do I send email message from ASP.NET?</dt>
        <dd>A.ASP.NET provides two namespace SystemWEB.mailmessage class and System.Web.Mail.Smtpmail class.</dd>
    </dl>
</form>

That's it what you have to do. Well done!