问题
I have a form that contains a row of inputs. One of those inputs is a jQueryUI autocomplete and each row has a button next to it that clones the row so that additional records can be created. I have the autocomplete set to recognize and bind to the newly created input:
$( '.input .my-field' ).on( 'focus', function() {
var $this = $( this );
$this.autocomplete({ ... });
});
What I'm finding is this:
- The autocomplete field in the first row works fine.
- The autocomplete field in the second row works fine if I didn't enter a value for that field in the first row.
- The autocomplete field in the second row doesn't work at all if I did enter a value in the first row.
The bottom line is that, if I create all of the rows first, everything works as expected, but this isn't the expected use case. Most folks will enter the first record, click to add another, enter those values, click to add another, rinse, repeat.
I'm still running it down, but I'm burning hours so I'm hoping someone will know what's going on and be able to jump in with a solution that doesn't require hours for me to work out on my own.
回答1:
There are two additional steps you must perform after cloning an autocomplete
input before re-creating it:
- Remove the
aria-haspopup
attribute; - Remove the
autocomplete
data.
Just calling autocomplete("destroy")
won't do, for some reason it destroys the original input instead of the clone. Working example at jsFiddle. Relevant code below:
var clone = $(...)
.clone(true)
.removeAttr("aria-haspopup")
.data("autocomplete",null);
来源:https://stackoverflow.com/questions/13593107/jqueryui-autocomplete-binds-to-first-element-only