如何在bootstrap popover中设置文本框值

时间:2017-01-18 18:37:01

标签: javascript jquery twitter-bootstrap

我在点击Anchor元素时显示bootstrap popover,如下所示。

Jquery的

$("[data-toggle=popover]").popover({
            trigger: 'click',
            placement: "top",
            html: true,
            content: function () {
                return $('#popover-content').html();
            }
        });

HTML

<div id="popover-content" class="hide">
    <div class="form-group">
        <input class="form-control" id="txtContent" type="text" />
        <button id="btnOk" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-ok"></span>&nbsp;
        </button>
        <button id="btnCancel" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove"></span>&nbsp;
        </button>
    </div>
</div>

<a href='#' class='btn-link' data-html='true' data-toggle='popover'>Sample text</a>

我想将popover内的文本框值(文本)设置为与锚元素的文本相同(即&#39;示例文本&#39;此处)。有人可以告诉我我该怎么做?

2 个答案:

答案 0 :(得分:1)

content内使用this,它是调用popover的元素引用。所以这里this将成为你场景中的锚元素。从anchor标记和add the value attribute获取文本到input element,然后返回$('#popover-content').html()

检查以下代码段。这可能会对你有帮助!

$(document).ready(function() {
  $("[data-toggle=popover]").popover({
    trigger: 'click',
    placement: "bottom",
    html: true,
    content: function() {
      var anchorText = $(this).text();
      $('#popover-content').find('input[id=txtContent]').attr('value', anchorText);
      return $('#popover-content').html();
    }
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<body>
  <div id="popover-content" class="hide">
    <div class="form-group">
      <input class="form-control" id="txtContent" type="text" />
      <button id="btnOk" type="button" class="btn btn-default">
        <span class="glyphicon glyphicon-ok"></span>&nbsp;
      </button>
      <button id="btnCancel" type="button" class="btn btn-default">
        <span class="glyphicon glyphicon-remove"></span>&nbsp;
      </button>
    </div>
  </div>
  <a href='#' class='btn-link' data-html='true' data-toggle='popover'>Sample text</a>
  <script>
  </script>

</body>

答案 1 :(得分:0)

正如文档所说,如果你想在popover中显示HTML,你必须通过title参数传递HTML,所以在你的情况下它代表:

<a href='#' class='btn-link' data-html='true' data-toggle='popover'
data-title="Sample text">Sample text</a>