Ask a Jedi: Checking Spry data for duplicates (and Spry 1.7 News)

Deli asked an interesting question. He wanted to know if there was a way to compare form data to data loaded in via Spry. My initial reaction was to show him this old blog entry that performs an AJAX request to see if a username exists. He wanted something that would work with a dataset though. Here is what I came up with. I began with a simple XML data set:

<kids> <kid> <name>Jacob</name> <age>8</age> </kid> <kid> <name>Lynn</name> <age>7</age> </kid> <kid> <name>Noah</name> <age>6</age> </kid> </kids>

And then used this in an HTML page like so:

var dsRows = new Spry.Data.XMLDataSet("test.xml", "/kids/kid");

I printed out the kids names:

<div spry:region="dsRows"> <div spry:state="loading">Loading - Please stand by...</div> <div spry:state="error">Oh crap, something went wrong!</div> <div spry:state="ready">

&lt;span spry:repeat="dsRows"&gt;
{name} is {age} years old&lt;br/&gt;



And finally, I followed this up with a form to allow someone to add a new kid (if only it were that easy):

<form> New Kid: <input type="text" name="newname" id="newname" /> <input type="button" value="Add" onClick="checkName()" /> </form>

Notice the onClick to run checkName. Let's look at that:

function checkName() { var name = Spry.$("newname").value; if(dsRows.getDataWasLoaded()) { data = dsRows.getData(); for(var i=0; i < data.length; i++) { if(data[i].name.toLowerCase() == name.toLowerCase()) { alert('This name already exists. Going to block form submission.'); return; } alert('This is a new name. Going to allow form submission!'); return; } } else { alert('Data not done loading. Please try again.'); } }

There are two main things in play here. I begin with a getDataWasLoaded call. This ensures that data was fully loaded. If it was, I run getData(). This returns a simple array of data based on my dataset. At that point, it's just a quick loop and string comparison.

Note - I would not use this form of checking if you were not displaying the data on the page. If you really just wanted to check for duplicate data, than I'd use the method I described in the other blog entry. Certainly if you had 10 million kids, you don't want to load that into the client.

Note for Spry 1,7 news - the Spry team released a small 1.7 preview. This update removes the necessity (in most cases) to load the xpath library.

Like This?

If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can also subscribe to the email feed to get notified of new posts.