[jQuery] autocomplete -- elegant way to manipulate results?
Hello,
I have begun to migrate from Scriptaculous because its Autocomplete's
support for IE6 is not all it's cracked up to be. However Prototype
has eloquence that I like, and I am wondering -- having read some docs
-- if there's a more elegant way in jQuery to do what I need to do.
When the user selects an item from the list resulting from the Ajax
call, I need to snag data out of it and insert a new DOM element with
it, as well as a link to remove that element should the user change
her/his mind. Specfically, I need a hidden field holding an id number
for submission and a string/name for display. With Scriptaculous, your
server-side script is supposed to return a finished HTML <ul> element,
so what I did was something like
foreach ($results as $row) {
echo "<li id=id_{$row->id}>$row->lastname, $row->firstname</li>"
}
Then, (with Scriptaculous.Autocompleter) after the user updates the
element, your callback gets passed to it the <li> DOM element the user
selected, so it's cake to pull out its id attribute and then insert
your DOM elements using the Prototype Element API
But... I gather from reading http://docs.jquery.com/Plugins/Autocomplete
etc that your server should output lines of text and let the
autocompleter wrap them in <ul><li>...</ul> tags. Unable to figure out
what else to do, I am having my server send the record id inside a
span element with its CSS display set to none, and in my callback I am
parsing out the id number with regexp matching. Then I am creating DOM
elements with raw HTML and string concatenation. It works, but is
ugly, error-prone and hard to read. Is there a more elegant way in
jQuery?
$("#deft_name").autocomplete('/requests/defendants/
autocompletedeftnames')
.result(function(event, data, formatted) {
event.target.value = '';
var matches = data[0].match(/(.+)<span[^>]*>(\d+)<\/span>/i);
if (matches.length != 3) { return alert("Error: could not parse "
+ data); }
$('#defendants').append(
'<div id="deftDiv_' + matches[2] + '"><a title="Click to remove
this defendant" href="javascript:void(0)">[x]</a> ' +
matches[1]+'<input type="hidden" name="deft_ids[]"
value="'+matches[2]+'"/><br/></div>\n'
);
$('#deftDiv_' + matches[2] + ' > a').click(function(e){ $
(this).parent().remove();} );
});
// testing what gets submitted...
$('#submitButton').click(
function(e) {
$.post("test.php", $('#myForm').serialize(), function(data){
alert(data);
});
}
);