Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Friday, May 18, 2012

Read hidden field value in asp.net from jquery

Often we are confused about how to read values set in asp.net HiddenField from jquery and use the values in the web form. Many-a-times we see the threads over the asp.net forums about the difficulties associated with reading asp.net HiddenField values. I have tried to give easy and fast way to read values and set values of hidden filed in asp.net using jquery.
You may first download the latest jquery file from jquery.com.
asp.net webform - design page
<body>
    <form id=\"form1\" runat=\"server\">
    <div>
    <asp:HiddenField ID=\"HiddenField1\" runat=\"server\" />
    <asp:Label ID=\"lblSiteName\" runat=\"server\"></asp:Label>
    </div>
    </form>
    <script type=\"text/javascript\" src=\"js/jquery-1.3.2.min.js\"></script>
    <script type=\"text/javascript\">
        $(function () {
            //reading hidden field value
            var mySite = $(\'#HiddenField1\').val();
            //displaying the value in an asp.net Label control
            $(\'#lblSiteName\').html(\'My site is: \' + mySite);
            //setting value of HiddenField control
            $(\'#HiddenField1\').val(\'New site is: http://asp.net\')
        });
    </script>
</body>
asp.net webform - code page (in c#)
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            HiddenField1.Value = "http://dotnetspidor.blogspot.com";
        }
    }
Known issue
If you have put the asp.net HiddenField control below the script tags, you may end up reading 'undefined' values. To solve the issue, I recommend putting the hidden fields at the top of the page just below the form tag.
Further, if you are using asp.net Master Page, please make changes in the jquery codes respectively. In such case, I  recommend the following syntax:
var mySite=$('[id$=HiddenField1]').val();
The system $= means the value that end with HiddenField1. This works since you usually see the id HiddenFiled1 used with master page rendered as ctl00_ContentPlaceholder1_HiddenField1.

Happy programming!!
Shout it

Friday, April 20, 2012

Flexible jquery based modal box or popup box -ColorBox

I have been using the jquery plugins for long. Many times I do need to implement facebook-like photo viewer in gallery pages. Similarly, mostly in admin pages of my asp.net web applications, I frequently us modal pop-ups for various purposes like ajax loading of content, iframe loading from other internal pages, confirmation and error show ups. Typically I used to go for separate plugins for the purpose. Lately I found the ColorBox plugin that satisfies both the needs. In one sense, this is a framework for me. You can visit  ColorBox and explore it.

Lets look at the features the ColorBox jquery plugin possesses.
  • Supports photos, grouping, slideshow, ajax, inline, and iframed content.
  • Lightweight: 10KB of JavaScript (less than 5KBs gzipped).
  • Appearance is controlled through CSS so it can be restyled.
  • Can be extended with callbacks & event-hooks without altering the source files.
  • Completely unobtrusive, options are set in the JS and require no changes to existing HTML.
  • Preloads upcoming images in a photo group.
  • Well vetted. ColorBox is one of the top jQuery plugins.
For jquery 1.3.2+, ColorBox has its older version, whereas for jquery 1.4.3+, ColorBox has its news version.
Meantime, you may also enjoy browsing jquery with asp.net tips in this blog. To sate the appetite of enthusiasts, I have also posted a bunch of javascript with asp.net related tips and tricks which you may find useful in your asp.net web development career. Cheers! kick it on DotNetKicks.com

Tuesday, November 22, 2011

Working with dropdownlist or combobox using jquery

More often programmers need to work with dropdownlist or combobox using jquery. We need to manipulate the dropdownlist options using jquery scripting. And it is the case that almost always we don't remember how to implement jquery selector. And for all of my readers, who are enthusiastic programmers and/or designers, and for myself, I am discussing in this post the actions with jquery to manipulate asp.net dropdownlist options.




Now append another option using jquery.
$('[id$=ddlTest]').append('');
[Why am I using the selector syntax $('[id$=ddlTest]') instead of $('#ddlTest')? We use #ControlID to select a control with specified id. $= means 'select a control whose id ends with specified value. If you are using master page, the rendered id of the dropdownlist is preceded with some text.] Now get the selected value from the dropdownlist.
var selVal=$('[id$=ddlTest]').val();
Now get the selected texct from the dropdownlist.
var selTxt=$('[id$=ddlTest] option:selected').text();
Now, select a value programmatically.
var selTxt=$('[id$=ddlTest]').val('Nepal');
And I hope you are comfortable with detecting through jquery when the use selects an item. Good luck!kick it on DotNetKicks.com

Thursday, September 29, 2011

Disable button in asp net web page to prevent multiple clicks


When a user clicks a button and the response is slow, there are chances that user may click the button again. The scenario may occur both when the button postbacks synchronously or asynchronously. This type of multiple clicks could be prevented if we could just disable the button just after the first click and enable it again when the processing is done. This is quite easy to implement the task in both the cases: synchronous and asynchronous postbacks.
Before we jump on the topic, you may learn how to click a button on enter key press in an asp.net textbox control. Similarly you may be interested in displaying google search-like watermark in an asp.net textbox control. Both the tutorials help you work with asp.net button control more interactively.
Fig. 1: Just after clicking asp.net button

Fig. 2: After postback occurs

If you are using ajax processing on button click, just disable the button when it is clicked and enable it when the ajax processing is done. If you are using full postback on button click, you may just make the button invisible using client-side-scripting when the click occurs. And you don't need to worry about making it visible since after postback the page will be rendered again, with the button visible as usual. In the snippet below I have shown how to 'disable' (in fact disabling won't work since the server side event is not firing) the asp.net button from client side when it is clicked. 
1. Add reference to jquery file

2. Design the web form
   
                           
   
   
3. Write the client scripting function with jquery

4. The code-behind.
protected void Button1_Click(object sender, EventArgs e)
    {
        lblMsg.Text +="Current time : "+ DateTime.Now.ToLongTimeString()+"
";
    }

That's all. When you click the button you catch the client side click event and make the button just invisible. Meantime show 'processing' or similar message. If you love ajax loading image, generate one and show it. From codebehind I have just displayed current time in a label.
Happy Bijaya Dashami (Dashain - the greatest festival of Hindus)!
kick it on DotNetKicks.com

Friday, December 18, 2009

Toggle image using jquery for animated hide show in asp-net

Web masters find it attractive to mark or indicate some text in a page as special part. For example a featured product in a shopping cart would hold a finished featured icon image at its side. Similarly we see New image icon blinking at the side of some product or text. It is sometimes better by far to use such animated images to draw user's attention. How would you do this using jquery? The simple answer is that- toggle the image based on its display status, in a regular interval.

There exists a simple method in jquery plugin that accomplished this task:

$('my-image-selector').toggle();

Let's look at the simple example.

<table>
<tr>
<td>This is some test news.</td>
<td style="height:45px"><img id="newImage" src="../images/new.jpg"
alt="New!" height="40px" width="40px"/></td>
</tr>
</table>

<script type="text/javascript">
$(function(){
setInterval(imageFlickr,300);
});

function imageFlickr()
{
$("#newImage").toggle(200);
}
</script>

 

In the page, I have added an image in a column of a table. Please use your own image (perhaps some 'New' image, as in the image above). Note the javascript setInterval() method that calls the function imageFlickr() every 300ms. In the method, we have the line:

$("#newImage").toggle();

The $(selector).toggle(interval) method toggles the show/hide property of the element. In the code, I haven't used the interval argument of toggle method. The interval in milliseconds defines the fade-in or fade-out speed of the element. Try this once and you will see great effect:

$("#newImage").toggle(200);

You are warmly welcome to share your experiences. You can start discussion by adding comments from the form below. You can help spreading out the words by bookmarking this article to
any of your favourite bookmarking site!

Happy Programming!

kick it on DotNetKicks.com

Wednesday, October 28, 2009

jQuery Mutually exclusive checkboxes in asp.net

We often see radio buttons to implement single choices out of many in web forms. Wouldn’t it be better if we could imply ‘choose one option from many’ using checkboxes? I have implemented such mutually exclusive checkboxes in asp.net using jquery. This certainly is not any new practice. We have already seen such mutually exclusive checkboxes in asp.net ajax, and perhaps there are others also. But achieving this functionality using a lightweight javascript library like jquery would be a benefit. So let’s start the race.

First of all, let me present the design philosophy of this realization of mutually exclusive checkboxes.

1. We will have a group of checkboxes with same css class name. We will not need the id of checkboxes besides for associating label to display text and make label clickable.

2. For our example, initially we will check one of the checkboxes. You may wish not to and this will work.

3. We can add any number of such groups of checkboxes but each group will have distinct class name. For example, one group of checkboxes can have class name ‘class1’ and other can have ‘class2’ and so on.

4. When a checkbox is checked, if it is already checked nothing will happen, otherwise this checkbox will be checked and all other checkboxes having the same class name as of this checked one will be unchecked.

5. If a checkbox is unchecked, we re-check it, since we want at least one checkbox checked. We can let a checkbox get unchecked if our requirement does not demand at least one option checked, but for this tutorial we will not let so.

By this time we have realized the need and design philosophy of implementing mutually exclusive checkboxes in asp.net using jquery. Now let’s proceed on.

We need the latest version of jquery which is available here [latest version is jquery 1.3.2 till date].


Fig:1 jQuery library added in asp.net website project

Now reference the jquery library file in the head section of the design page.


Fig:2 jQuery libray referenced in the header section of asp.net design page

Here goes the design markup code in the aspx page.

<form id="form1" runat="server">
<asp:Label ID="lblResult" runat="server" ForeColor="Green"></asp:Label>
<div id="toggleContainer">
I like to mix
<input type="checkbox" id="aspnet" class="firstClass" checked="checked" runat="server"/>
<label for="aspnet">asp.net</label>
<input type="checkbox" id="php" class="firstClass" runat="server"/>
<label for="php">php</label>
<input type="checkbox" id="jsp" class="firstClass" runat="server"/>
<label for="jsp">jsp</label>
<input type="checkbox" id="asp" class="firstClass" runat="server"/>
<label for="asp">asp</label>
<br /><br /> with
<input type="checkbox" id="jquery" class="secondClass" checked="checked" runat="server"/>
<label for="jquery">jquery</label>
<input type="checkbox" id="javascript" class="secondClass" runat="server"/>
<label for="javascript">pure javascript</label>
<input type="checkbox" id="aspnetajax" class="secondClass" runat="server"/>
<label for="aspnetajax">asp.net ajax</label>
<input type="checkbox" id="thirdajax" class="secondClass" runat="server">
<label for="thirdajax">third party ajax</label>
<br /><br />
<asp:Button ID="btnResult" runat="server" OnClick="btnResult_Click" Text="Show Result!" />
</div>
</form>


Fig:3 Mutually exclusive checkboxes at initial state

As shown in the page code above, we have three different groups of checkboxes having class names firstClass and secondClass. Each group has one checkbox checked initially.

Now is the time to use and understand the jquery script in the page. Here is the complete code in the script block.

<script type="text/javascript">
$(document).ready(function(){
//toggle all checkboxes in toggleContainer div
$('#toggleContainer :checkbox').bind('change',function(){
var thisClass=$(this).attr('class');
if($(this).attr('checked'))
{
$('#toggleContainer :checkbox.'+thisClass+":not(#"+this.id+")").removeAttr('checked');
}
else
{
$(this).attr('checked','checked');
}
});
});
</script>

Explanation of jquery code snippet

1. We put all the codes that are required to run at the page load within document’s ready event handler code block, so the first line.

2. toggleContainer is the div element we put all our checkboxes. We have done this to avoid collision with other checkboxes in the page. For all checkboxes [as by :checkbox selector] within this div element we bind change event. So, the following code block will execute when any checkbox is checked or unchecked.

3. In the change event, we read the class name of the current checkbox in thisClass variable. Note that we are reading the value of attribute class [as by .attr method, used to get or set value of an attribute]

4. If this checkbox has attribute ‘checked’, this means we are checking this checkbox exclusive of others in its group. So we uncheck all checkboxes other than itself having class name of this checkbox [stored in variable thisClass]. How we achieve this- uncheck all checkboxes other than this? Answer is: using : not[itself] selector. This selector excludes the matching dom element from the result.

5. If this class has no ‘checked’ attribute, this means the previously checked chexbox has been tried to uncheck which we prevent by re-checking this checkbox since this violates our design philosophy.

That’s all.

Reading Result

Remember the Show Result button in the pages? Yeah, we will publish the result as of user’s selections. Here goes the code-behind code snippet.

//prints your choices in the result label
protected void btnResult_Click(object sender, EventArgs e)
{
string result = "Oh, you like to mix ";
if (asp.Checked)
result += "asp";
else if (aspnet.Checked)
result += "asp.net";
else if (php.Checked)
result += "php";
else
result += "jsp";

result += "
with ";

if (jquery.Checked)
result += "jquery ajax!";
else if (javascript.Checked)
result += "pure javascript ajax!";
else if (aspnetajax.Checked)
result += "asp.net ajax!";
else
result += "other third party ajax!";

result += "
";

lblResult.Text = result;
}


Fig:4 Mutually exclusive checkboxes in action

Conclusion

In this simple yet descriptive tutorial we implemented mutually exclusive checkboxes in asp.net using latest javascript jquery library. Since we used class property of checkboxes, we have been able to implement this with any number of distinct groups of checkboxes. If you enjoyed this tutorial, please spread the words: bookmark this, share your opinions via comments or email this article etcetera! Happy programming!

kick it on DotNetKicks.com

Popular Posts

Recent Articles