Archive for the 'jQuery' Category

Using Jeditable for inline editing

Thursday, February 4th, 2010

Using the Jeditable plugin for jQuery enables inline editing of a block of text. This makes it easy to take a static view and simply drop in editability. Say we start with the following HTML:

<label>Name:</label> <span class="employeeName">Ben Scott</span><br/>
<label>Rating:</label> <span class="employeeRating">Highly awesome</span>

We want to be able to edit the employeeName and employeeRating spans. We need two actions (asssuming an MVC framework) to update the name and rating. The URLs might be something like /employee/set_name/{id} and /employee/set_rating/{id}. Each action should accept HTTP POST, take the new value in $_REQUEST['new_value'] or similar, and return a HTTP status of 200 on success and 500 on failure, with the error message in the response. For example, using Slab (my PHP5 MVC framework, in development) the set_name action might be like this:

class EmployeeController extends AppController {
	function set_name($id) {
		$this->Employee->save(array(
			'id' => $id',
			'name' => $this->data['new_value']);
		));
		return $this->ajaxSuccess($this->data['new_value']);
	}
}

Slab catches uncaught exceptions and returns an AJAX failure with the exception message as the body of the response.

To hook up the fields to the actions, modify the HTML to include the URLs to the actions. While this means the markup has behavioural elements and isn’t purely presentational (and has a non-standard attribute), it makes the script a bit simpler and easy to move into a static .js file, and is a quick way to get a page working.

<label>Name:</label> <span class="employeeName" editUrl="/employee/set_name/7">Ben Scott</span><br/>
<label>Rating:</label> <span class="employeeRating" editUrl="/employee/set_rating/7">Highly awesome</span>

Now for the script itself:

$(function(){
	$('.employeeName, .employeeRating').editable(
		function(value, settings) {
			return $.ajax({
				url: $(this).attr('editUrl'),
				data: { 'new_value': value },
				async: false,
				type: 'post'
			}).responseText;
		}, {
			indicator: 'Saving...',
			tooltip: 'Click to edit',
			onblur: 'submit'
		}
	);
});

The first argument is a function that returns the new value of the field. This is important when doing things like replacing line breaks with <br/> which we’re not worrying about, but it also gives us the ability to write our own AJAX code. By default Jeditable makes assumptions about how the update is done. The async option in the call to $.ajax() blocks until the call returns, and lets the function return the response of the AJAX call. The second argument are options to set some text to show while calling the update function, the tooltip to display when hovering over the span, and to submit changes on blurring the input which makes it seem a bit more usable when there are multiple fields.

Cliche – an extremely simple view template engine for jQuery

Monday, December 21st, 2009

I’ve written a very simple plugin for jQuery that takes a template and a model and returns a view of the model. To make sure it worked I wrote some tests and examples, and since I did that I figured I would write a little mini-site. The plugin itself is pretty straightforward:

(function($){
	$.fn.cliche = function(model){
		var template = $(this).html();
		template = template.replace(/%7C/g, '|');	// pipes in a href like <a href="|... get converted to %7C, convert it back
		template = template.replace(/\|.*?\|/g, function(f) {
			var val = model;
			var fieldParts = f.replace(/\|/g, '').split('.');
			for (var i = 0; i < fieldParts.length; i ++) {
				val = val[fieldParts[i]];
			}
			return val;
		});
		return template;
	};
}(jQuery));

It is used by setting up a template (putting it into a script type="text/html" block is convenient and hides it from display) and calling cliche(model) on the jQuery object:

<div id="output">
	<ul></ul>
</div>
<script type="text/html" id="testTemplate">
	<li id="item|id|"><a href="viewItem?id=|id|">|name|</a></li>
</script>
<script type="text/javascript">
	$('#output ul').append(
		$('#testTemplate').cliche({
			id: 1, name: 'Lorem'
		})
	);
</script>

Cliche is licensed under a Creative Commons Attribution 2.5 Australia license. Check it out at http://cliche.belfryimages.com.au.

Form validation with jQuery

Wednesday, December 9th, 2009

Every time I’ve implemented client-side form validation I’ve started from scratch and done it a little differently. Usually it devolves into a messy set of if statements and duplicated code. Here’s my latest method, which separates the validation rules from the processing. It uses jQuery because if you’re not using a Javascript library you should be. This will only handle relatively simple validation cases.

So start with a form:

	<form id="mailingListSubscription" action="subscribe.php">
		Name: <input type="text" name="name" id="name" /><br />
		Email: <input type="text" name="email" id="email" /><br />
		Phone: <input type="text" name="phone" id="phone" /><br />
		<button type="submit">Subscribe</button>
	</form>

All fields are required, and I’m going to use some magical regex (found on the interthingy somewhere) to validate the email address. This script sets up the rules:

	var rules = [
		{ id: 'name', test: function(val) { return val != ''; }, msg: 'Please enter your name' },
		{ id: 'email', test: function(val) { return val.search(/^[^@]+@[^@]+.[a-z]{2,}$/i) != -1; }, msg: 'Please enter a valid email address' },
		{ id: 'phone', test: function(val) { return val != ''; }, msg: 'Please enter your phone number' }
	];

Each rule has the id of the form element being tested, a message that gets displayed on failing the rule, and a function that validates the value of the form element. I also could add multiple rules for the one input.

This script sets up the submit handler for the form, which does the validation using the array of rules set up above:

	$(function(){
		$('form#mailingListSubscription').submit(function(){
			for (var i = 0; i < rules.length; i ++) {
				var rule = rules[i];
				var target = $('#'+rule.id);
				if (!rule.test(target.val())) {
					alert(rule.msg);
					target.focus();
					return false;
				}
			}
			return true;
		});
	});

On a test failing, the rule’s msg value is shown and the target of the test gets focus. This could be changed to something more user friendly like showing the message next to the target field.

Deleting items in a table with AJAX via JQuery

Sunday, November 29th, 2009

This is a very straight-forward tutorial on implementing a jQuery-driven ‘delete via AJAX’ feature. Say we have a plain HTML table containing a list of items and a ‘Remove’ link. I’m not going to describe the back-end, but I’m assuming something groovy like CakePHP or ASP.NET MVC. I’ve also assumed that the delete request always succeeds and never returns an error, which may not be the case. The script itself is a more than required but is my preferred method as I can extend the elements in the UI fairly easily.

	<table>
		<tr><td>Chickpeas</td>      <td><a href="/items/delete/1" class="delete">Delete</a></td></tr>
		<tr><td>Garlic</td>         <td><a href="/items/delete/2" class="delete">Delete</a></td></tr>
		<tr><td>Olive oil</td>      <td><a href="/items/delete/3" class="delete">Delete</a></td></tr>
		<tr><td>Tahini</td>         <td><a href="/items/delete/4" class="delete">Delete</a></td></tr>
		<tr><td>Cumin</td>          <td><a href="/items/delete/5" class="delete">Delete</a></td></tr>
		<tr><td>Lemon juice</td>    <td><a href="/items/delete/6" class="delete">Delete</a></td></tr>
	</table>

The delete hrefs (/items/delete/XX) link to an action or page that deletes the specified item and returns a HTTP status of 200 (OK). If the action just redirected to the current page then this table should work as it stands, which is probably a good way to check that everthing works as expected without involving AJAX features. If you just want to set up the client side without implementing any server-side code, create the following in delete_test.php and use it for the delete links:

<?php header('HTTP/1.1 200 OK'); ?>

Make sure that jQuery 1.3+ has been included in the page and add the following:

<script type="text/javascript">
$(function(){
	var ui = {
		init: function(){
			$('a.delete').live('click', ui.delete_click);
		},

		delete_click: function(){
			link = this;
			$.get(link.href, function(data, status) {
				$(link).parents('tr').remove();
			});
			return false;
		}
	};

	ui.init();
});
</script>

Very basic stuff but it works. It could be jazzed up by fading out the items first or updating a status label. If there is a significant delay between calling the delete action and getting a response the user may not think anything has happened, so perhaps the delete link should change or be disabled.

jQuery Blink plugin

Thursday, October 8th, 2009

I love this Blink plugin by John Boker. Not because it’s something that should ever be used (I don’t think that was the intent). It’s just a good, simple reference plugin.