简体   繁体   中英

How can I use autocomplete with event binding?

this is my first post here, I've found answers here before I have a form where I can add fields that have autocomplete.
Instead of adding the autocomplete to each field as I create them, is it possible to use event binding to add the autocomplete?
I am a newbie when it comes to events in javascript.
This is what I have done to add a new line, using event binding (works perfectly).

$(function() {
    $('input[name=addItem]')
        .bind('click', function() {
            var line = $('#list > div').size()+1;
            divId = 'line-'+line;
            var divCloned = $('#line-1').clone();
            divCloned.attr('id', divId);
            $('#list').append(divCloned);
            var inputs = $(divCloned).children('input').get();
            for (var i in inputs) {
                inputs[i].value='';
                inputs[i].id = inputs[i].id.replace(/\d+/, line);
                inputs[i].name = inputs[i].name.replace(/\d+/, line);
            }
            this.blur();
        });
});  

I'm not even sure if I have presented my question in a proper way.
Thank you.

If I understand your question correctly, you want your autocomplete to be applied to all input fields? You can do that by generalizing your selector, so instead of adding the event to $('input[name=addItem]') (Meaning: To all tags of type "input" with an attribute "name" set to "additem") you can for example use $('input[type=text]') which will bind your event to all input-tags with attribute "type" set to "text".

Depending on your application, would you want to change the suggested auto-completes based on which input-field is being clicked on? That'd need more logic in your event handler.

Option 1: Copy the original autocomplete

You can make a .clone() that includes event handlers using .clone(true) :

var divCloned = $('#line-1').clone(true);

This should include the autocomplete for #line-1 , so with the line above replacing the corresponding line in your code you should be all set.



Option 2: Create a new autocomplete with different options

If you want to change the autocomplete functionality, you can just set it again:

var divCloned = $('#line-1').clone(); // <== Don't copy the event handlers.

// ... do things, set variables, append divCloned, whatever

  // Now set the autocomplete with different options from the original
divCloned.autocomplete({ ... });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM