Archive for the ‘jQuery’ category

Using jQuery to tidy up missing Images

February 21st, 2012

I’m working on a page that pulls photo’s from a file share on a server by the format of “firstname-lastname-dept.png”. Now 9 times out of 10 this works fine but on the odd occasion an image doesn’t exist.  Now I could do it via c# in code behind to check it exists or I could do it via jQuery.  For this post I am going to do it with jQuery as we could really build upon this post quite easily.

Before we capture the missing Images

I’ve created a simple page with BootStrap and get the following:

Photo Viewer jQuery Image Loaded Not Found

As you can see 2 of the images aren’t found and the alt tag is displayed. This can easily be avoided by adding a couple lines of jQuery magic.

Source/Demo – http://dev.siphilp.co.uk/jQuery-Check-Image-Error.htm

Adding in the jQuery capture

For this we’re going to be using the function “error”.

The error event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly. * find here - http://api.jquery.com/error/

A very simple implementation is as follows:

$(function () {
   if ($.browser.msie) {
        $('img').each(function () {
    	if (this.readyState == 'uninitialized') {
    	       $(this).attr('src', 'images/not-found-image.jpg');
    	   }
    	});
      }
$('img').error(function () {
  $(this).attr('alt', 'image not found').attr('src', 'images/not-found-image.jpg');
 });
});

 

Internet Explorer doesn’t like the Error function so I added a check (line 3-7). After the DOM has loaded it goes through each of the images on the page and checks the readyState. Any images not loaded will be replaced with the not-found-image.

With the above in place we get a nicer look and feel to the page with further options available should we wish to take this little project further.

Photo Viewer jQuery Image Loaded Replaced

I have had a couple of ideas in which I am going to expand on this, I’ll be posting these shortly.

If you want to see the complete source and demo – http://dev.siphilp.co.uk/jQuery-Check-Image-Loaded.htm

Be Sociable and Share!

Customise Subtext Core Pages – Part 1

September 13th, 2011

Subtext LogoI have about 23 posts sitting in drafts in relation to my subtext skin bonanza. It takes a while to go through each skin, test it, write it up and package it up so please bare with me. I do plan on catching up soon.

I wanted to take time out from subtext themes for a moment and go over a topic that I think will be of some use to such webmasters that use subtext on a multi-blog platform. Customising Subtext core pages.

What pages am I talking about here?

In this part I am going to cover pages that are visible to non-authenticated users:

  • Login Page jQuery UI – Part 1
  • Login Page New Design – Part 2
  • 404 Page – Part 3
  • Error Page  – Part 4

Customise the page

Login Page

For anyone logging in to a subtext blog you’ll be confronted with the following screen.

SubtextDefaultLogin

While the above page is minimalistic and straight forward you might want to tweak it more to your users/clients. Where do we begin?

Using jQuery UI

To start with we will make backups before making any changes. We are interested in the login page found Solution –> Subtext.Web –> aspx –> login.aspx. I first add the jQuery and jQuery UI javascript references to the bottom of the login.aspx page:

</form>
<script type=”text/javascript” src=”jquery.min.js”></script> _fcksavedurl=””jquery.min.js”></script>”
<script type=”text/javascript” src=”jquery-ui.min.js”></script>
</body>
</html>

I am referencing them locally for now so i can work offline. Before deploying I would point my code to Google cdn.

Preparing the UI theme

subtext ui file listingLooking at the jQuery themes I decided to go with the Flick theme as the colours will go with the Subtext logo. Before I can use the theme I created a folder within the aspx folder to house the UI files.

Going with a custom build of jQuery UI as we’re only interested right now on the tabs and button widgets. Extracting the custom build and putting the files in the newly created directory.

All the files are now in place just the matter of making the page come alive. Within the header of the page just under the line that declares the “login.css” we add the following line:

<link rel=”Stylesheet” type=”text/css” href=”<%= VirtualPathUtility.ToAbsolute(“~/aspx/UI/jquery-ui-1.8.16.custom.css”) %>” />

Bringing the page to life – Tabs

The login page now has all the references it needs to use the widgets from the jQuery UI so next we’re going to bring the page to life.

A couple of changes and the results are looking fantastic:

Normal Sign in

Please-Sign-In-Tab

Sign in with OpenId

openid-signin-tab

Code Changes to login.aspx

I have highlighted the code needed to get the above working. At the end of the post I’ll post a download link.

<div id=”logo”></div>
<div id=”tabs”>
<ul>
<li><a href=”#nSign”>Please Sign In Below</a></li>
<li><a href=”#oSign”>Sign In with OpenID</a></li>
</ul>

<fieldset id=”nSign”>
<legend>Please Sign In Below</legend>
…..
</fieldset>
<fieldset id=”oSign”>
<legend>Sign In with OpenID</legend>
….
</fieldset> </div>
</div>
</form>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js”></script>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js”></script>
<script type=”text/javascript”>
$(function () {
$(“#tabs”).tabs();
});
</script>

Bringing the page to life – Buttons

We talked above about adding jQuery UI tabs to the login page.   The next stage is we’re going to transform the plain buttons as seen above into nicer looking elements.

The cascading style sheet and JavaScript files have all been added already so it’s the matter of adding a single line and voila.

<script type=”text/javascript”>
$(function () {
$(“#tabs”).tabs();
$(“input:submit”).button();
});
</script>

You can see the results below.

Please-Sign-In-Tab-button

To download the login page for all the above click here.

Next step we could implement an icon on the button. For more info check out : http://jqueryui.com/demos/button/#icons

Be Sociable and Share!

Using jQuery/css to make your radio button lists look good

December 12th, 2010

This post was influenced by some prototypes I have been building over the last couple of weeks. Radio button lists used correctly are a fantastic way to get information from your users.

Boring Radio Button List

One problem with radio button lists is that no matter how you present them either in a list format going up and down or horizontal they look boring.

Boring Radio Button List

Good looking Radio Button List

I was thinking of a way to make the above a little bit more exciting and make it more interesting to the end user.  I decided to make it more graphic this is where jQuery goodness and a dab of css comes in. With about 15 lines of code the outcome looks fantastic, who says Radio Button Lists need to be boring?

Cool Radio Button List

Solution

HTML

Looking below you can see that I have added the onclick event to the link but this could be added to any of the elements.

   1:  <h2>Boring radio button List</h2>   
   2:  <ul>
   3:  <li>Please choose your favourite Browser:</li>
   4:  <li><input type="radio" name="ImgCh" value="Chrome" />Chrome</li>
   5:  <li><input type="radio" name="ImgCh" value="InternetExplorer" /> Internet Explorer</li>
   6:  <li><input type="radio" name="ImgCh" value="FireFox" />Firefox</li>
   7:  <li><input type="radio" name="ImgCh" value="Safari" />Safari</li>
   8:  </ul>
   9:  <h2>Jazzed up by jQuery Radio button list</h2>
  10:  <ul>
  11:  <li>Please choose your favourite Browser:</li>
  12:  <li><a href="#" onclick="SelectOpt('ImgChoice','Chrome');"><img src="Images/Chrome.png" alt="Chrome"  /></a>
<input type="radio" name="ImgChoice" value="Chrome" class="d" /> Chrome</li>
  13:  <li><a href="#" onclick="SelectOpt('ImgChoice','InternetExplorer');">
<img src="Images/InternetExplorer.png" alt="Internet Explorer" /></a>
<input type="radio" name="ImgChoice" value="InternetExplorer" class="d"/> Internet Explorer</li>
  14:  <li><a href="#" onclick="SelectOpt('ImgChoice','Firefox');"><img src="Images/FireFox.png" alt="Firefox"  /></a>
<input type="radio" name="ImgChoice" value="Firefox" class="d" /> Firefox</li>
  15:  <li><a href="#" onclick="SelectOpt('ImgChoice','Safari');"><img src="Images/Safari.png" alt="Safari"  /></a>
<input type="radio" name="ImgChoice" value="Safari" class="d" /> Safari</li>
  16:  <li id="Selection"></li>
  17:  </ul>
  18:  <a href="javascript:Toggle();">Show above radio buttons</a>

Script

Line 5 has a function SelectOpt which takes 2 properties: rlName and value. The “rlName” is the name of the radiobutton list we’ll be searching to match the other property “value”. When the value is found the appropriate css class is applied to the elements parent in this case the “li” tag and the hidden radio button is checked.

   1:    <script type="text/javascript">
   2:          function Toggle() {
   3:              $('.d').toggle();
   4:          }
   5:          function SelectOpt(rlName, value) {
   6:              $('input[name="' + rlName + '"]').each(function () {
   7:                  if ($(this).val() == value) {
   8:                      $(this).attr('checked', true).parent().addClass('h');
   9:                  } else {
  10:                      $(this).attr('checked', false).parent().removeClass('h');
  11:                  }
  12:              });
  13:              $('#Selection').text("You selected : " + value);            
  14:          }   
  15:      </script>

CSS

   1:   <style type="text/css">
   2:       body{font-family:Arial;font-size:80%;}
   3:      .h{border:2px solid #569700; background-color:#76AF2C;}  
   4:      .d{display:none;}
   5:      li{ list-style-type:none;width:250px;padding:5px;}
   6:      img{border:1px solid #b5b5b5;}
   7:      </style>

Next Steps

In a future post I will take the above further so that if JavaScript is disabled then the page renders the boring list.

I have created a demo of the above and i have added in the ability to see the actual Radio Buttons when you make a selection.

View the demo

Be Sociable and Share!

How to call JavaScript functions based on the querystring

April 26th, 2009

jQuery Plugin – Fun with Query String Object

I have been working on an internal application which uses ajax and modal popups so that the user/manager/administrator doesn’t need to navigate to different pages to do different actions.  While this looked the part and done everything it said on the tin I ran into a problem. When a user acknowledged an event that needs authorisation a email is sent to the appropriate manager asking for action.  This email needed to contain a link that when the manager clicked it, the appropriate section was shown.

No point in re-inventing the wheel and writing individual pages so I had an idea about using querystrings to show the appropriate modal popup.  I found a nice little jQuery plugin called query object.  As you can see from the documentation it’s very easy to use.

If the link in the email is showing the manager a listing of say New Contacts added

http://app/view/manager/?showModal=LoadNewContacts

Within the document ready we could do the following:

   1:   $(document).ready(function() {
   2:         var section = $.query.get('showModal');       
   3:             var allowedFunctionsArray = ['LoadNewContacts()', 'AlertMe()'];           
   4:             if ($.inArray(section, allowedFunctionsArray) != -1) {
   5:                 eval(section);
   6:            }
   7:        });
   8:   
   9:        function AlertMe() {
  10:            alert('this is an alert');
  11:         }   
  12:         function LoadNewContacts() {           
  13:             $('#Contacts').toggle();
  14:         }

Line 2 assigns the local variable section with the value of the querystring “showModal”.  Notice live 5 with the eval(section).

“The eval() function evaluates a string and executes it as if it was script code.” – w3 Schools

The querystring value is the name of the function we want to call and the eval function makes this possible.  However, using the eval() function can lead to cross site scripting(XSS). I have added a check to only allow what I want to run, in this case only the following two functions can be called “LoadNewContacts” and “AlertMe”. What you’re not seeing is the fact that the files that have these functions are served via a secure http handler based on windows authentication and that checks are in place to make sure managers can only see/action what they’re meant to. Is simple and effective.

View demo of running different functions via querystring

If you would like to see more posts in relation to jQuery please use the following link: View jQuery post listing

Be Sociable and Share!

jQuery – Revisit – Fun with Radio Button lists, checkboxes and labels

April 19th, 2009

In my previous post I outlined how easy it was to grab text from a label tag associated to a form input element.

I have quickly thrown together a demo page that shows a “tra la” aspect.

All I have done here is added in a couple of styles, a new radio list for the colour selection and an express delivery option.  The green div shown above the colour radio button list has it’s background colour controlled by whatever colour the user selects.

Change Background colour

Add an onclick event that captures the value in this case colour and passes it into a simple function:

 1:  $("input[name*='grpColour']").click(function() {
 2:             SetTShirtDivColour($(this).val());
 3:         });

The function is is very straight forward:

 1: function SetTShirtDivColour(colour) {
 2:         $('#tshirtColour').css("background-color", colour).text(colour).css("color", "white").css("font-weight", "bold");
 3:         var border = "2px solid " + colour;
 4:         $('#ColourHolder').css("border",border);
 5:      }

The above adds styles to the tshirtColour and ColourHolder div using jquerys ability to chain methods.  As you can see on line 2 the colour passed into this function is used when setting the background colour.

Adding a popup div

To add a quick popup I have attached an onclick event to the Yes radio item Express delivery.

 1:   $('#RadioDelYes').click(function() {
 2:             ShowHideDisclaimer();
 3:         });

Along with some css we can do the below. The ShowHideDisclaimer method just toggles the visibility of the background black div “transp” and the disclaimer div “ExpressDelivery”. I could of added a “you clicked Yes/No” to the disclaimer div but I wanted to show that you can attach the onclick event to a single item within a list.

  function ShowHideDisclaimer() {
        $('#transp').toggle();
        $('#ExpressDelivery').toggle();

    }

View live demo and see full source code.

Be Sociable and Share!

jQuery – Fun with Radio Button lists, checkboxes and labels

April 13th, 2009

Previously I have written about how to attach an onclick client event to a radio button list on databound and adding some flare to show what the user has selected.

In this post I am going to use jQuery to attach the onclick events to a radio button list and to a group of checkboxes.

jquery label text

Looking at the picture above. When the user selects one of the radio list items the message at the top is created outlining the items value and the text in associated label control. In this case “Glasgow Item” is in the label and “Glasgow” is the value of the control. With the checkboxes, everytime a user checks an item an unordered list item is created with the text within the associated label and the value of the item. As shown above 3 items have been selected that are shown in the listing.

The messages/list could be styled and used in many occasions giving any web form more “tra la”. In my next post I’ll put together a mock page that is styled up. A live demo of above picture can be seen here. Onto the code:

HTML:

 1: <div id="Message"></div>
 2: <ul id="listM"></ul>
 3: <input id="grpLocation_0" type="radio" name="grpLocation" value="Edinburgh" />
 4: <label for="grpLocation_0">Edinburgh Item</label>
 5: <input id="grpLocation_1" type="radio" name="grpLocation" value="Glasgow" />
 6: <label for="grpLocation_1">Glasgow Item</label>
 7: <input id="grpLocation_2" type="radio" name="grpLocation" value="Aberdeen" />
 8: <label for="grpLocation_2">Aberdeen Item</label>
 9: <input id="grpLocation_3" type="radio" name="grpLocation" value="Scotland" />
 10: <label for="grpLocation_3">Scotland Item</label>
 11: <hr />
 12: <input id="Radio1" type="checkbox" name="Location2" value="Edinburgh" />
 13: <label for="Radio1">Edinburgh Item</label>
 14: <input id="Radio2" type="checkbox" name="Location2" value="Glasgow" />
 15: <label for="Radio2">Glasgow Item</label>
 16: <input id="Radio3" type="checkbox" name="Location2" value="Aberdeen" />
 17: <label for="Radio3">Aberdeen Item</label>
 18: <input id="Radio4" type="checkbox" name="Location2" value="Scotland" />
 19: <label for="Radio4">Scotland Item</label>

Script:

 1: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
 2: <script type="text/javascript">
 3:     $(document).ready(function() {
 4:         $("input[name*='grpLocation']").click(function() {
 5:             var defaultValue = $("label[for*='" + this.id + "']").html();
 6:             var defaultm = "You have chosen : ";
 7:             $('#Message').html('').html(defaultm + defaultValue + ' | Value is : ' + $(this).val());
 8:         });
 9: 
 10:         $("input[name*='Location2']").click(function() {
 11:             GetCheckedValues();
 12:         });
 13: 
 14:     });
 15: 
 16:     function GetCheckedValues() {
 17:         $('#listM').html('');
 18:         $("input[name*='Location2']").each(function() {
 19:         if (this.checked == true) {
 20:             var defaultValue = $("label[for*='" + this.id + "']").html();
 21:                 $('#listM').append('<li>'+ defaultValue + ' | Value is : ' + $(this).val() + '</li>');
 22:             }
 23:         });
 24: 
 25:     }
 26: </script>

Breaking down the script.

When the page is loaded jQuery adds the onclick events to the group of radio buttons. When a radio item is selected the script  finds the associated label (line 5) and grabs the text. Next couple of lines sets up the message div by displaying the text from the label and the items value $(this.).val().

The checkbox functionality differs as more than one item can be selected. When the page is loaded jQuery finds the checkboxes(line 10) and attaches “GetCheckedValues()” function to the onclick event. When the user checks/unchecks an item this function is called.  The function goes through each appropriate checkbox object (line 18) and if the checkbox is checked the label text and the value is added to the unordered list (listM).

I would thoroughly recommend the following book if your looking to learn jQuery : jQuery in Action by Bear Bibeault and Yehuda Katz.

UPDATE: New Post – jQuery – Revisit – Fun with Radio Button lists, checkboxes and labels

Be Sociable and Share!

Javascript unit testing frameworks

February 9th, 2009

Myself and Simone have been in discussions about creating a jQuery plugin for many months now.  With real life, time on both parts hasn’t been on our side. Simone has co-authored a MVC book entitled “Beginning ASP.NET MVC”. I’ve been busy with work, getting fit, holidays, and other projects (more details coming soon).

We’ve both now managed to make a start on the plugin which resulted in me looking at unit testing frameworks for JavaScript. I was quite surprised to find the amount I did hence this short and sweet post.

List of JavaScript testing frameworks

With the project being jQuery orientated we’re going to use QUnit for our testing needs.  As a personal learning curve I am going to play about with YUI test suite and JsUnit framework on some other projects. I would like to compare the differences, advantages and disadvantages to using each one.

Be Sociable and Share!

jQuery – making it easy – basic manipulation – Part 1

October 29th, 2008

Over the last couple of weeks I have been doing alot of work on a UI for client/matter conception application at my work involving javascript and the almight framework jQuery.  I have done a couple of posts in relation to jQuery before:

  1. Subtext Galleries, using jQuery for funk
  2. Adding a Javascript onClick event to a Radio Button List Item on DataBound
  3. Adding a Javascript onClick event to a Radio Button List Item on DataBound Pt 2

Also my 1st ever patch to subtext project uses jQuery.

After receiving countless emails about some of the above I thought I would post a couple of articles to outline how jQuery can make any developers life easier. This post is aimed at developers who haven’t looked at jQuery before or people who want quick and easy examples. This is a very basic article and I will be going into more depth of the fQuery framework over the next couple of months.

How I am going to do this is show the javascript equivalent and the jQuery statement. Worst case is you walk away from reading this article knowing how to manipulate html elements.  If you’re doing any manipulation to the dom it’s always worth putting in validation to make sure the element exists.  Also note that the object that’s being passed to the function is the elements Id.

This first part will compare the following:

  • Show/Hide an element
  • Toggle an element
  • Adding a css class to an element
  • Removing a css class from an element
  • Adding them together

 

show/hide an element – Javascript

function HideElement(object)
{
document.getElementById(object).style.display = ‘none’;
}

 

function ShowElement(object)
{
document.getElementById(object).style.display = ‘block’;
}

 

show/hide an element – jQuery

function HideElementjQuery(object)
{
$(‘#’ + object).hide(‘fast’);
}

Usage: <a href=”#” onclick=”javascript:HideElementjQuery(‘objectid’);”>Click Me</a>

function ShowElementjQuery(object)
{
$(‘#’+ object).show(‘fast’);
}

Usage: <a href=”#” onclick=”javascript:ShowElementjQuery(‘objectid’);”>Click Me</a>

Thoughts on show/hide an element

While both are straight forward you’ll notice that on the jQuery functions there is a “show(‘fast’)”.  jQuery gives the developer options to play with.  This can be the speed in which the object is hidden or shown, it can also be the effect you’d like to use when it appears and disappears. More information can be found UI/Effects – jQuery

Toggle an elements display property – Javascript

function toggleElement(object)
{
    if(document.getElementById(object).style.display != ‘none’)
        {
            document.getElementById(object).style.display = ‘none’;
        }else{
            document.getElementById(object).style.display = ”;
        }
}

 

Toggle an elements display property – jQuery

function toggleElementjQuery(object)
{
$(‘#’ + object).slideToggle(‘slow’);
}

Usage: <a href=”#” onclick=”javascript:toggleElementjQuery(‘objectid’);”>Click Me</a>

Thoughts on toggle an elements display property

Straight away you see a reduction in code here. How simple is that. jQuery does the checking for you and dictates what state the object should be in.

Adding a css class to an element – Javascript

function addcssclass(object,cssclass)
{
document.getElementById(object).setAttribute(“class”,cssclass);//For FF
document.getElementById(object).setAttribute(“className”,cssclass);//For IE
}

Adding a css class to an element – jQuery

function addcssclassjQuery(object,cssclass)
{
$(‘#’+object).addClass(cssclass);
}

Usage: <a href=”#” onclick=”javascript:addcssclassjQuery(‘objectid’,'cssclass’);”>Click Me</a>

Thoughts on adding a class to an element

Again another reduction in code and jQuery takes away the worry of what browser the user is using and adds the class. Another flaw with the javascript code is that if the object had a css class by default then this is removed and the new one assigned.  jQuery adds to any css classes that may already be assigned to the object.  If we added a method to check for existing css classes and to add our new class then we’d run into may more lines of code that would have to be cross browser compatiable.

Removing a css class from an element – JavaScript

function removecssclass(object,cssclass)
{
document.getElementById(object).removeAttribute(“class”,cssclass);//For FF
document.getElementById(object).removeAttribute(“className”,cssclass);//For IE
}

Removing a css class from an element – jQuery

function removecssclassjQuery(object,cssclass)
{
$(‘#’+object).removeClass(cssclass);
}

Usage: <a href=”#” onclick=”javascript:removecssclassjQuery(‘objectid’,'cssclass’);”>Click Me</a>

Thoughts on removing a class from an element

As with adding a css class jQuery has taken away the worry of what browser the user is using.

Adding them together

This I am going to add a class while toggling the elements display property.

function ToggleAddClass(object,cssclass)
{
$(‘#’+ object).slideToggle(‘slow’).addClass(cssclass);

}

Usage: <a href=”#” onclick=”javascript:ToggleAddClass(‘objectid’,'cssclass’);”>Click Me</a>

function ShowElementRemoveClass(object,cssclass)

{

$(‘#’+ object).show(‘fast’).removeClass(cssclass);
}

Usage: <a href=”#” onclick=”javascript:ShowElementRemoveClass(‘objectid’,'cssclass’);”>Click Me</a>

Thoughts on adding them all together

As you can see from the above piece of code all that’s needed is to add the effects needed to the object.

Final Thoughts

This post outlines the tip of the iceberg but as you can see one liners can do so much without having to worry about what browser is being used, or having to write long complicated functions.  Part will be looking at input Element Manipulation and validation.

Be Sociable and Share!

Adding a Javascript onclick event to a Radio Button List Item on DataBound Pt 2

January 15th, 2008

A while back I wrote a quick article about adding a javascript onclick event to each individual radio button list “Adding a Javascript onclick event to a Radio Button List Item on DataBound“.

I was speaking to an early learner via email regarding what we would use this type of scenario for so thought I would put together something very quickly just to maybe flair some creativity.

Demo

The following demo uses the JQuery library.  What I have done is simply change the onclick event from showing an alert box to populate a div, a textbox and a hyperlink with the value of the radio button. 

All I have done is add the JQuery library to the page and changed

 <script language=javascript type="text/javascript">
    function ShowExt(object)
    {
    alert("Value Clicked :" + object);
    }
    </script>

to the following

<script language="javascript" type="text/javascript">
    function ShowExt(object)
    {
    $('#JqueryMessageBox').html('This is a div showing value :' + object);
    $('#JqueryMessageBox').show('slow').animate({opacity:1.0},3000).fadeOut('slow');
    $('#textdemo').show('slow').animate({opacity:1.0},3000).fadeOut('slow');
    $('#textdemo').val('Textbox value : ' +object);
    $('#vistscotland').show('slow');
    $('#vistscotland').text('Link showing : ' + object);
    }
    </script>

For the above script to work we also need to add in the following html under the radiobutton list

    <div id="JqueryMessageBox" style="margin-top:20px;margin-left:10px;background-color:white;border:2px solid #83A7BF;padding:5px;width:50%;display:none;">
        </div>
        <input type="text" maxlength="55" name="textdemo" id="textdemo" style="display:none;margin-top:10px;margin-left:10px;" />
        <a href="http://www.visitscotland.com" id="vistscotland" style="display:none;margin-top:10px;margin-left:10px;"></a>
    

The style options contain alot of formatting options but really all that is needed is the display:none. In this case I’ll keep it kind of pretty.  All the Javascript is doing is looking for the Id’s of the elements under the Radiobutton list, running through an effect and then populating the element with the value of the object that called the onclick event.  Nothing complicated, short and sweet.  I would like to iterate even though it’s obvious the event/effects won’t work if javascript is disabled.

To see the demo in action : http://dev.siphilp.co.uk/OnClickRadioButtonListwithjquery.aspx

Related Posts:

 

Be Sociable and Share!

Adding a Javascript onclick event to a Radio Button List Item on DataBound

November 8th, 2007

This is very straightforward and can add some extra functionality to your forms in the sense of if this value is selected show that div.

Within the asp.net page we add the control to the page:

<asp:RadioButtonList ID="grpLocation" runat="server" RepeatDirection="Horizontal"
OnDataBound="grpLocation_onDataBound">
</asp:RadioButtonList>

Within the code behind we add some listitems to the Radio button list:

ListItem A = new ListItem("Edinburgh", "Edinburgh");
ListItem B = new ListItem("Glasgow", "Glasgow");
ListItem C = new ListItem("Aberdeen", "Aberdeen");
ListItem D = new ListItem("Scotland", "Scotland");
grpLocation.Items.Add(A);
grpLocation.Items.Add(B);
grpLocation.Items.Add(C);
grpLocation.Items.Add(D);
grpLocation.DataBind();

In the code behind we add the following code to the grpLocation_onDataBound event:

 RadioButtonList rbl = (RadioButtonList)sender;
        foreach (ListItem li in rbl.Items)
        {
            li.Attributes.Add("onclick", "javascript:ShowExt('" + li.Value + "')");
        }

What the above code is saying is add the attribute “onclick” to each list item within the RadioButtonList with a value of “javascript:ShowExt(‘value’)”.

For the above example to work we’ll also need to add the javascript function “ShowExt” to the page:

 <script language=javascript type="text/javascript">
    function ShowExt(object)
    {
    alert("Value Clicked :" + object);
    }
    </script>

What the above code will do is show an alert box with the value of the radio item. Short, simple and sweet.

Click here to see a live demo

related posts:

Be Sociable and Share!