Register the dynamic control using jquery for autocomplete
i am creating the textboxes dynamically using jquery on a button click.
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<div id="lblCustName">
</div>
</td>
<td>
<div id="lblRemove">
</div>
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="Add" id="AddRow" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" id="SaveCustomers" />
</td>
</tr>
开发者_如何学JAVA </table>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
//validate post form
$("#CustomersForm").validate({ ignore: ":not(:visible)" });
//Initialize the dynamic id
_DynId = 1;
//Click Event for Customers
$('#AddRow').click(function(e) {
$('#lblCustName').append('<div id="lblCustName' + _DynId + '" style="height:20px;padding-left:10px;">' + '<input type="text" name="CustName" id="CustName' + _DynId + '" class="required" value="" title="*" />');
$('#lblRemove').append('<div id="lblRemove' + _DynId + '" style="height:20px;padding-left:10px;">' + '<img src="../../Content/Images/delete_icon.gif" onclick=Remove("' + _DynId + '"); title="Remove" id="iRemove' + _DynId + '"></img>');
_DynId += 1;
});
</script>
I am trying to add the textbox for customers dynamically. This is the sample html for the functionality of adding customers for a report processing,... I need to give the autocomplete option for the textboxes.
I have used the below script for that:
$.getJSON("/User/GetAllCustomers/?t=" + new Date(), {},
function(data) {
if (data != null) {
$("input:text[name=CustName]").autocomplete(data, { mustMatch: false, matchContains: 4, max: 50,
formatItem: function(row) {
if (row.CustomerName!= "") {
return row.CustomerName;
}
},
formatResult: function(row) {
return row.CustomerName;
}
}).result(function(e, row) {
//do something
});
}
});
The autocomplete is not working for the dynamically added controls.
I am trying for any possibility to register the dynamically added controls to the form, so that the autocomplete will work for the dynamically added controls
The problem is that when you bind that autocomplete it's binding to the fields that match the selector when the function is ran. If you add something later that also matches it won't automatically bind.
For basic jQuery events there's a Live binding that lets you do this automatically, but autocomplete won't work through this - basically your only choice is to bind a new auto-complete each time you add a new text field
EG: Add to the AddRow function:
$("#lblCustName" + _DynId + " input[name=CustName]").autocomplete(...);
(Obviously replacing ... with the parameters you want)
You'll likely want to put your data object that you pulled back from the webservice in a global variable to support this, and probably the same with the autocomplete options (just to avoid code duplication).
精彩评论