Autocomplete Not Working On Cloned Input Element
Autocomplete working perfect on first input element but after making clone of this input autocomplete not working for new
Solution 1:
After digging i found this solution.
- Autocomplete add an class to a input element.
- When we cloned input element then that class also present already.
- so before initialise autocomplete to an cloned element we first need to remove that class "ui-autocomplete-input";
- then call autocomplete function on that input.
Solution 2:
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 withclone-*
value by default. Here * will be incrementing numbers 2, 3, 4 etc. - Click on
clone-2
and try to change value to something starting witha
,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');
});
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><scriptsrc="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script><linkrel="stylesheet"href="//jqueryui.com/jquery-wp-content/themes/jqueryui.com/style.css"><linkrel="stylesheet"href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"><divclass="ui-widget"><labelfor="tags">Tags: </label><inputid="tags"><divid="container"></div><buttonid="tryClone">
Try clone and bind
</button></div>
Post a Comment for "Autocomplete Not Working On Cloned Input Element"