Reputation: 589
I'm new to jquery, I'm working on a web page which needs generating text boxes dynamically with autocomplete facility. I don't know how bind event with generated textbox. my code looks as follows:
$(document).ready(function () {
var counter = 1;
$(".addButton").live("click", function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.html('<TABLE><TR><TD>' + '<input type="text" name="textbox' + counter + '" id="textbox' + counter + '" value="" ></TD> <TD><a href="#" value="addButton" class="addButton">Add</a> </TD></TR></TABLE>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
});
and post query
function fillTextBox(text) {
$.ajax(
{
type: 'POST',
url: '@Url.Action("_AutoCompleteAjaxLoading", "CommandEntity")',
async: true,
data: { text: text},
dataType: "json",
traditional: true,
success: function(data) {
//what I should do here?
},
error: function(xhr, ajaxOptions, thrownError) {
}
});
}
Upvotes: 0
Views: 4382
Reputation: 1038840
You could use the jquery ui autocomplete plugin:
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult _AutoCompleteAjaxLoading(string term)
{
var data = new[] { "item 1", "item 2", "item 3" };
return Json(data, JsonRequestBehavior.AllowGet);
}
}
View:
<script type="text/javascript">
$(function () {
setupAutoComplete();
var counter = 2;
$('#TextBoxesGroup').delegate('a.addButton', 'click', function (evt) {
evt.preventDefault();
$('<table/>', {
html: $('<tr/>', {
html: $('<td/>', {
html: $('<input/>', {
type: 'text',
id: 'textbox' + counter,
name: 'textbox' + counter
})
}).after($('<td/>', {
html: $('<a/>', {
href: '#',
'class': 'addButton',
text: 'Add'
})
}))
})
}).appendTo('#TextBoxesGroup');
setupAutoComplete();
counter++;
});
});
var setupAutoComplete = function () {
$(':text[name^="textbox"]').autocomplete({
source: '@Url.Action("_AutoCompleteAjaxLoading")',
minLength: 2,
select: function (event, ui) {
}
});
};
</script>
<div id="TextBoxesGroup">
<table>
<tr>
<td>
<input type="text" name="textbox1" id="textbox1" value="" />
</td>
<td>
<a href="#" class="addButton">Add</a>
</td>
</tr>
</table>
</div>
Upvotes: 3
Reputation: 797
Im not really sure what do you need either. Try adding a line like
$('#textbox' + counter).keypress( function(){
// here trigger autocomplete event
} )
Or
$('#textbox' + counter).keypress( fillTextBox( $(this).val() ) )
Upvotes: 1