See the code snippet below, where I have used the jQuery UI along with jQuery UI autocomplete. The functionality works, Please ignore the missing style, you can easily fix it.
How it works:
At first, I cloned the input element and then rebind the autocomplete on it and then enable autocomplete on it. The snippet that you are interested is as follows:
$(tag2).autocomplete({
source: availableTags
}).autocomplete('enable');
You can run and test the snippet. Please let us know whether it works for you or not.
Sample Run
- Run the
Run code snippet
- Click on
Try clone and bind. You will see input field with clone-* value by default. Here * will be incrementing numbers 2, 3, 4 etc.
- Click on
clone-2 and try to change value to something starting with a, b. You will see autocomplete appearing on the fields.
Try to study the code and tweak it to your need. Let us know if you still feel confused on it.
$( function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$("#tags").autocomplete({
source: availableTags
});
var count = 1;
var cloneId = 'clone-';
$('#tryClone').on('click', function() {
var tag2 = $('#tags').clone();
tag2.removeAttr("id");
count += 1;
var elementId = cloneId + count;
$(tag2).attr("id", elementId).val(elementId);
$(tag2).autocomplete({
source: availableTags
}).autocomplete('enable');
$(tag2).appendTo('#container');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//jqueryui.com/jquery-wp-content/themes/jqueryui.com/style.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
<div id="container">
</div>
<button id="tryClone">
Try clone and bind
</button>
</div>