Reputation: 159
I'm looking for a solution to attach the jQuery autocomplete function to a dynamically generated input . So the name cannot be used in the javascript section like in the example : $("#completeMe").autocomplete({ . ...
, from here http://carlhoerberg.com/how-to-use-jquery-ui-autocomplete-with-aspnet
My idea is to call a javascript function when text is changing in the dynamically generated text input :
<%= Html.TextBoxFor(x => x.Name,new { onkeypress="doSomething(this)"}) %>
The dynamically inputs are generated after this example :<http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/>
and in the doSomething() method I will have a reference to the sender input given by "this" .
but further . . I don't have a clue how to attach the autocomplete function to the sender.
Do you have any idea ?
Upvotes: 0
Views: 1692
Reputation: 8397
The basic problem here is that you can't attach event handlers (etc) to elements that aren't there yet. The best way to approach this problem is to call the autocomplete() function on the new elements as they are generated.
Using the example you posted:
$("#addItem").click(function() {
$.ajax({
url: this.href,
cache: false,
success: function(html) {
$("#editorRows").append(html);
/* !!! */ $("#editorRows").find("input").last().autocomplete();
}
});
return false;
});
Note my three exclamation marks. Remove these, but observe the line. Here you call the autocomplete function on your latest added input row, enabling it to use the autocomplete plugin as well.
I hope this answers your question, good luck!
Upvotes: 1
Reputation: 1436
Id selectors are just one of available jQuery selectors, you can use jQuery "class selectors" instead. so any of generated input would has a specific css class name like toautocomplete
:
<input id='someunknownid1' type='text' class='toautocomplete' />
<input id='someunknownid2' type='text' class='toautocomplete' />
and then apply autocomplete plugin on using :
$(".toautocomplete").autocomplete();
Upvotes: 0