How to implement jQuery UI autocomplete function to an input in a Modal appended after loading the document?

StackOverflow https://stackoverflow.com/questions/21977841

I'm trying to bind the jQuery UI autocomplete function to a input element that was appended after loading the document. I've tried several solutions but still got stuck. I'm using the following code:

// When user click "Add" button to add a new networks value
$(".modal").on("click", ".add-network-value", function(e){
  input = '<input class="edit-input form-control autocomplete-input" type="text" name="'+ table_name + '" size="' + input_width +'">';        
  autocomp_opt={
    source: ["aaa","bbb","ccccc"]
  };
  item = '<div class="networks-item"></div>';
  input = $(input).autocomplete(autocomp_opt);
  item = $(item).append(input);
  $(this).parents(".sub-content").append(item);
}

Update

Well, it turns out that the code itself is correct. The problem is that the input box is in a "modal" that has a higher z-index value than jQuery-ui's autocomplete div's z-index. You need to higher the z-index value of the jQuery-UI autocomplete CSS file or lower the z-index of the modal.

有帮助吗?

解决方案

It looks like you are using jQuery UI autocomplete function on a "modal". The drop-down box added by the autocomplete module may have not displayed on the top of your modal but it actually gets created - that may be the reason why you cannot see the list.

其他提示

Are the Javascript variables table_name and input_width defined? And are the classes on the HTML defined correctly?

The following code should work,

HTML:

<div class="sub-content">
    <div class="modal">
        <button class="add-network-value">Add</button>
    </div>
</div>
<div class="networks-item"></div>

Javascript:

var table_name  = 'test';
var input_width = 10;
$(document).ready(function() {

    // When user click "Add" button to add a new networks value
    $(".modal").on("click", ".add-network-value", function(e){
        var input = '<input class="edit-input form-control autocomplete-input" type="text" name="'+ table_name + '" size="' + input_width +'">';        
        var autocomp_opt={
            source: ["aaa","bbb","ccccc"]
        };
        var item = '<div class="networks-item"></div>';
        input = $(input).autocomplete(autocomp_opt);
        item = $(item).append(input);
        $(this).parents(".sub-content").append(item);
    });
});

See here for a Fiddle.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top