Home > Software design >  Set attributes to the button but only works when I click it twice
Set attributes to the button but only works when I click it twice

Time:11-17

I have set some attributes to my button with some bootstrap elements, however when I click the button for the first time it didn't work. I need to click somewhere outside the button, and click the button again.

I had solve this by calling the function in onl oad and call it again in button, but now I'm in a situation that I can't do that anymore, so I was wondering is there any other ways to solve the problem?

Here is my code: https://jsfiddle.net/a22177861/x381z0h6/6/

HTML:

 <button type="button" class="btn btn-warning" onclick="PopOver(this,'Hi','Thank','You');">ClickMe!</button>

JS:

function PopOver(myObj, mgr, Adate, Vdate) {
        $(function () {
            myObj.setAttribute("data-container", "body");
            myObj.setAttribute("data-toggle", "popover");
            myObj.setAttribute("data-placement", "bottom");
            myObj.setAttribute("data-html", "true");
            myObj.setAttribute("data-trigger", "focus");
            myObj.setAttribute("title", "otherInfo");
            myObj.setAttribute('data-content', "MGR:" mgr "<br />DATE1:" Adate "<br />DATE2:" Vdate);

            $("[data-toggle='popover']").popover();
        });
    } 

Any help would be greatly appreciated!

CodePudding user response:

I suggest you write your code in a friendlier way. Some dead fields can be written directly in HTML

    <button type="button" class="btn btn-warning" data-container="body" data-toggle="popover" data-trigger="focus" data-placement="bottom" data-html="true" title='otherInfo' onclick="PopOver(this,'Hi','Thank','You');">ClickMe!</button>

function PopOver(myObj, mgr, Adate, Vdate) {
  myObj.setAttribute('data-content', "MGR:" mgr "<br />DATE1:" Adate "<br />DATE2:" Vdate);
  $("[data-toggle='popover']").popover('show');
} 

CodePudding user response:

This $('[data-toggle="popover"]').popover() in your code initializes the popover, so you have to click twice to trigger it.

According to Bootstrap's popover documentation:

Reveals an element’s popover. Returns to the caller before the popover has actually been shown (i.e. before the shown.bs.popover event occurs). This is considered a “manual” triggering of the popover. Popovers whose both title and content are zero-length are never displayed.

You can use .popover('show') to manually trigger the popover.

It will be like this:

function PopOver(myObj, mgr, Adate, Vdate) {
  myObj.setAttribute("data-container", "body");
  myObj.setAttribute("data-toggle", "popover");
  myObj.setAttribute("data-placement", "bottom");
  myObj.setAttribute("data-html", "true");
  myObj.setAttribute("data-trigger", "focus");
  myObj.setAttribute("title", "otherInfo");
  myObj.setAttribute('data-content', "MGR:" mgr "<br />DATE1:" Adate "<br />DATE2:" Vdate);

  $("[data-toggle='popover']").popover('show');
} 
  • Related