简体   繁体   English

Bootstrap Typeahead无法与动态输入配合使用

[英]Bootstrap Typeahead not working with dynamic inputs

I got and input by default when the page is loaded like this: 默认情况下,页面加载时我得到并输入:

<input type="text" class="form-control input-sm productName" id="" placeholder="Search..." />

And the typeahead code I'm using is this 我正在使用的预输入代码是这样的

$.get('../search_product.php', function(data){
    $(".productName").typeahead({ source: data });
},'json');

This is working fine with my input by default but after I add new elements using append it is not working anymore, how can I make this works with new elements? 默认情况下,这对于我的输入工作正常,但是在使用append添加新元素后,它不再起作用了,如何使它与新元素一起工作?

And I would like to know how to send with a variable the value that i'm typing in the input because I'm doing this for now in the server side just an example 我想知道如何使用变量发送我在输入中输入的值,因为我现在在服务器端只是一个例子

echo json_encode(array('hi', 'hi 2', 'hi 3', 'hi 4'));

I mean how to send a param like 我的意思是如何发送像

$query = $_GET['param'];

I hope you can help me, thanks. 希望您能帮助我,谢谢。

UPDATE: 更新:

 $('#containerProducts').append('<div class="row m-t-5">' +
                                        '<div class="col-sm-offset-2 col-sm-4"><input type="text" class="form-control input-sm productName" id="" placeholder="Search..." /></div>' +
                                '</div>'
                            );

In Javascript, when an element is created, things are not automatically bound to it. 在Javascript中,创建元素时,事物不会自动绑定到该元素。 You should isolate your typeahead initialization in its own function, and then anytime elements are created, you call it to initialize the new elements. 您应该在自己的函数中隔离可提前输入的初始化,然后在任何时候创建元素时,都调用它来初始化新元素。 For example: 例如:

function initTypeahead() {
    // Should probably add code here to only grab elements that are not already initialized
    var elements = $('.productName');
    $.get('../search_product.php', function(data){
        $(elements).typeahead({ source: data });
    }, 'json');
}

Then when you initialize your page, you would call that to init the initial elements. 然后,当您初始化页面时,您将调用它来初始化初始元素。

$(document).ready(function() {
    initTypeahead();
});

If you add a new element, you would call it again: 如果添加新元素,则将再次调用它:

$('#containerProducts').append('<div class="row m-t-5">' +
    '<div class="col-sm-offset-2 col-sm-4"><input type="text" class="form-control input-sm productName" id="" placeholder="Search..." /></div>' +
    '</div>'
);
initTypeahead();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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