Bootstrap标签输入

时间:2015-08-17 11:46:39

标签: javascript asp.net twitter-bootstrap bootstrap-tags-input

我从以下资源下载了 bootstrap-tagsinput 库的源JS和CSS: http://timschlechter.github.io/bootstrap-tagsinput/examples/

在我的asp.net网站上,我通过以下方式使用它:

 <asp:TextBox ID="txtCompany" style="font-size:x-large" runat="server" data-role="tagsinput" CssClass="form-control" placeholder="Add Company" />

 <script type="text/javascript">
    $('input #txtCompany').tagsinput();
    alert($('input #txtCompany').val());
 </script>

但警报实际上应该返回我创建的代码,而是返回: undefined

JS是用Master Page编写的。 Master Page中也提到了所有CSS和JS引用。

这里有什么问题?

编辑:

TextBox呈现如下: enter image description here

编辑:

使用以下jQuery代码,我能够检索div的内容。

 $('#btn').click(function () {
                var div = document.getElementById("div");
                var spans = div.getElementsByTagName("span");

                for (i = 0; i < spans.length; i++) {
                    alert(spans[i].innerHTML);
                }
            });

但问题是它返回以下内容:

enter image description here

还会显示另一个空警报!我不知道为什么!

2 个答案:

答案 0 :(得分:2)

您有2个选项 第一个是用浏览器中解析的id替换id

<asp:TextBox ID="txtCompany" style="font-size:x-large" runat="server" data-role="tagsinput" CssClass="form-control" placeholder="Add Company" />

<script type="text/javascript">
    $('input #ContentPlaceHolder1_txtCompany').tagsinput();
    alert($('input #ContentPlaceHolder1_txtCompany').val());
 </script>

或者您将在文本框中添加一个类作为第二个解决方案,并将jquery代码中的id替换为类名而不是id

<asp:TextBox ID="txtCompany" style="font-size:x-large" runat="server" data-role="tagsinput" class="form-control txtcomp" placeholder="Add Company" />

<script type="text/javascript">
    $('input .txtcomp').tagsinput();
    alert($('input .txtcomp').val());
 </script>

尝试它,我认为它会起作用

修改 您可以使用此功能在警报

中显示添加的项目值
 $('input').on('itemAdded', function (event) {
     alert(event.item)
 });

答案 1 :(得分:0)

您应该将属性ClientIDMode设置为“Static”以保留控件ID,而不使用父级占位符Id作为前缀。像这样:

<asp:TextBox ID="txtCompany" ClientIDMode="Static" style="font-size:x-large" 
runat="server" data-role="tagsinput" CssClass="form-control" placeholder="Add Company" />