Reputation: 101
how to add the auto-complete in this dynamically added Textbox? i have used this way $('#se').autocomplete();, but not getting that.
$(document).ready(function()
{
var counter = 2;
$("#addButton").click(function ()
{
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<input type="text" placeholder="Role" name="Role' + counter +
'" id="textbox' + counter + '" value="" > <input type="text"
placeholder="Search" name="search' + counter +
'" id="se" value="" > <input type="hidden" name="search' + counter +
'" id="se' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
$('#se').autocomplete();
counter++;
});
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1" class="form-inline control-group">
<%= text_field_tag('roles', nil,:id => 'textbox1')%>
<%= text_field_tag('search', nil,:id => 'se')%>
<%=hidden_field_tag(:id_search, value = "")%>
<input type='button' value='Add' id='addButton'>
</div>
</div>
Upvotes: 1
Views: 2509
Reputation: 123739
There were issues with string concatination and selection in your code:-
Main thing is $('#se' + counter).autocomplete({source: availableTags});
you weren't attaching counter here. And there was no source too. In the example i have just attached hummy source, it could be static source or ajax inyour case.
See Doc for more details...
Try this:-
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<input type="text" placeholder="Role" name="Role' + counter + '" id="textbox' + counter + '" value=""> <input type="text" placeholder="Search" name="search' + counter + '" id="se' + counter + '" > <input type="hidden" name="search' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
$('#se' + counter).autocomplete({source: availableTags});
counter++;
});
For more clarity you should use jquery element constructor and build the lements for more readeability Demo
var roleInput = $('<input/>',{
type:'text',
placeholder:'Role',
name:'Role'+counter,
id:'textbox' + counter
});
var searchInput = $('<input/>',{
type:'text',
placeholder:'search',
name:'search'+counter,
id:'se' + counter
});
var hidd=$('<input/>',{
type:'hidden',
name:'searchhid'+counter,
id:'searchhid' + counter
});
newTextBoxDiv.append(roleInput).append(searchInput).append(hidd);
newTextBoxDiv.appendTo("#TextBoxesGroup");
$('#se' + counter).autocomplete({
source: availableTags
});
counter++;
Upvotes: 1
Reputation: 36531
IDS should always be unique... since your are generating input with same id.. your HTML becomes invalid (though it works).. one way to make it work is to changes the ids to class...
<%= text_field_tag('search', nil,:class=> 'se')%>
...<input type="text" placeholder="Search" name="search' + counter + '" class="se" value="" >...
and use class selector for autocomplete,
$('.se').autocomplete();
Upvotes: 0