Search code examples
javascriptpopovercleave

Run js when pop over text input is loaded


Wanted to have cleave.js to format text input on the fly.

I have 2 text inputs

  1. HTML text input and
  2. also a pop over text input whenever search icon is clicked.

The issue is on popover text input where cleave text formating is not working.

I believe it could be related to the element hasn't exist somehow? I have try to listen to listener but no luck so far. .on('shown.bs.popover)

My code as as per below https://jsfiddle.net/fairul82/y3kf92oq/ Libraries used : cleave,js , bootstrap popover , jquery

 HTML
<div class="container">
 <h3>Bootstrap 3 Popover HTML Example</h3>
 <input type="text" class="input-element"><br>
 <ul class="list-unstyled">
 <li><a data-placement="bottom" data-toggle="popover" data- 
container="body" data-placement="left" type="button" data-html="true" 
href="#" id="login"><span class="glyphicon glyphicon-search" style="margin:3px 0 0 0"></span></a></li>
<div id="popover-content" class="hide">
  <form class="form-inline" role="form">
    <div class="form-group">
      <h1>
        My Content
      </h1>
      <input type="text" class="input-element"><br>
    </div>
  </form>
</div>

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

 $("[data-toggle=popover]").on('shown.bs.popover', function() {
 // alert('called back');
 const cleave = new Cleave('.input-element', {
 numeral: true,
   numeralThousandsGroupStyle: 'thousand'
 });
 });

 const cleave = new Cleave('.input-element', {
 numeral: true,
  numeralThousandsGroupStyle: 'thousand'
 });

Solution

  • Here is solution https://jsfiddle.net/ztkv8w60/19/

    According to authority document https://github.com/nosir/cleave.js, it has a note .input-element here is a unique DOM element. If you want to apply Cleave for multiple elements, you need to give different css selectors and apply to each of them.

    It is tricky question, because the bootstrap popover creates the same element as your specific div when the icon gets a click. Therefore there are two the same element, you have to point it out which element is in a popover.