Välj jQuery buttonset knapp programmatiskt

Jag hade ett problem idag. Jag hade skapat ett buttonset med jQuery och ville att en av knapparna alltid skulle vara förvald. Detta var dock enklare sagt än gjort. Det fanns ingen option (hoppas att det kommer) för att välja vilken knapp som skulle vara vald när sidan laddades.

Jag ville att det skulle se ut så här när jag laddade sidan:

Förvald knapp
Förvald knapp

Jag lyckades lösa detta på ett sätt som inte är optimalt, men det funkar.
Knepet är att utlösa Click() eventet på BÅDE labeln OCH radioknappen när sidan laddas.

Så här blev koden:

<html>
	<head>
		<link type="text/css" media="screen" rel="stylesheet" href="http://www.lundsbk.org/jquery_ui/css/theme/jquery-ui-1.8.9.custom.css" />
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
		<script type="text/javascript" src="jquery.easing.1.3.js"></script>
		<script type="text/javascript" src="jquery-ui-1.8.5.custom.min.js"></script>
		<title>Test!</title>
		<script type="text/javascript">
			$(document).ready(function()
			{
				//Create a buttonset
				$('#ButtonsDiv').buttonset();
 
				//Make sure the second button is always pre-selected 
				$('#Second').click(); 			//Click the second radio button
				$('#LabelForSecond').click();	//Click the second label
			});
		</script>
	</head>
	<body>
		<div>
			<div id="ButtonsDiv">
				<input type="radio" name="Buttons" id="First" /><label for="First" id="LabelForFirst">First</label>
				<input type="radio" name="Buttons" id="Second" /><label for="Second" id="LabelForSecond">Second</label>
				<input type="radio" name="Buttons" id="Third" /><label for="Third" id="LabelForThird">Third</label>
			</div>
		</div>
	</body>
</html>

JQueryUI broken theme

I realized something funny today about jqueryui. I’m using it on a site I’m working with and I was gonna change theme. I created a new theme with the tools on jqueryui.com and downloaded it. When I was going to download it I selected “Deselect all components” as I had no need for the javascript, I thought…
The problem is that you only get the CSS directly connected to the jquery components, so, if you’re gonna change theme, make sure you select all components you used last time

Using hosted jquery

En kort genomgång om hur och varför man ska använda googles jquery hosting istället för att ha filerna på den egna servern.

If you are using jquery or jqueryui then make sure that you don’t keep the library itself on your own server. Google, and other companies, are hosting the files you need to use jquery and jqueryui (google also hosts its own jquery-json library).

This has several advantages:

  • You don’t need to host the files yourself
  • You don’t need to care about users who can only download using a certain amount of connections to your server
  • Caching
  • The distance to your user (wherever your server is located, there is always a google server closer to your user)

This means that instead of writing like this:

<script type="text/javascript" src="/javascript/jquery-1.4.4.js"></script>

You write it like this:

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

Now you never have to care where you keep your jquery libs. You’ll also know that you’ll be cutting down loading time on your page as most users hopefully have the libraries cached on their computers. So all you have to do is change the version number whenever you feel like upgrading you libraries.

JQuery:
http://code.google.com/intl/sv-SE/apis/libraries/devguide.html#jquery

JQuery – Google JSON Library:
http://code.google.com/p/jquery-json/

JQueryUI:
http://ajax.googleapis.com/ajax/libs/jqueryui/[UI-VERSION]/themes/[THEME-NAME]/jquery-ui.css

The JQueryUI must be used with a defined theme (in the URL there is a [THEME-NAME] section which must be replaced with a propert theme name and UI-VERSION must be changed to version). Here’s a couple of the themes available (all can be found on this google blog). In general any theme name from the jqueryui.com theme gallery can be used:

A very basic jquery-plugin

This will be a short entry regarding how to create a very simple jquery plug-in. In this example I’ll create a plug-in which will lock text boxes to numeric input only (which can be useful if you want age input or something of the like).

The first thing you need to do is to create a ‘closure’ of the jQuery object. There are a lot of different libraries for javascript and the dollar sign can collide with these. So, to ensure that this won’t happen you can encapsulate it into a self-calling function, looking something like this:

(function($)
{
});

As we are writing a jQuery plug-in we’ll send the jQuery object as an argument. Without the self-caling it could also be written as:

function foo()
{
}

But then we’d had to call our plug-in our selves before we use it, and we don’t want that.
The plug-in itself will be added inside the encapsulation and it basically looks like this:

(function($)
{
	$.fn.numeric = function()
	{
		return this.each(function(idx, element)
		{
			$(element).bind('keydown', function(e)
			{
 
			});
		});
	}
})(jQuery);

$.fn.numeric = function(){} creates the plug-in. This is what you use on your element later (ex: $(‘.foo’).numeric()) to activate it.
It will loop through all elements it’s connected to and bind a keydown event to that element. Then we bind the keydown to each element it loops though and this is where we add our numeric-check, it looks like this:

...
$(element).bind('keydown', function(e)
{
	//8  = Backspace
	//46 = Delete
	if(e.keyCode == 46 || e.keyCode == 8) 
	{
		//Do nothing
	}
	else 
	{
		//48 = 0
		//...
		//57 = 9
		if(e.keyCode < 47 || e.keyCode > 58)
		{
			e.preventDefault();
		}
	}
});
...

We take in an event object from the keydown event. This object contains a property called keyCode. This property tells us which button it was that the user pressed to fire the event.
We check if the button is 46 (delete) or 8 (backspace) and if it is, we do nothing as these buttons are allowed (we could also have added ‘.’ if we want to allow decimals). Then we check if the key code is between 47 and 58 (0-9 key in the key code map) and if it isn’t, we exit the keydown event. This means that no command is sent to the end client (our input box).

The whole code, with bindings, looks like this:

(function($)
{
	$.fn.numeric = function()
	{
		return this.each(function(idx, element)
		{
		$(element).bind('keydown', function(e)
		{
			//8  = Backspace
			//46 = Delete
			if(e.keyCode == 46 || e.keyCode == 8) 
			{
				//Do nothing
			}
			else 
			{
				//48 = 0
				//...
				//57 = 9
				if(e.keyCode < 47 || e.keyCode > 58)
				{
					e.preventDefault();
				}
			}
		});
		});
	}
 
	$(document).ready(function()
	{
		$('.nummer').numeric();
	});
})(jQuery);

A demo can be found here: http://demo.maffelu.net/jquery/basicplugin.htm