Search code examples
javascriptbuttondynamics-crm

Create Button in CRM 2016 Form without a Field using Javascript


I had to create a button inside a lookup field i have followed this page http://bharathknight.blogspot.com/2015/03/create-button-inside-form-using.html i have added a event onchange the lookup value but the first alert is hitted but the second none and no button is displayed pleaase help me i'm stucked here

function createButton() { 
      alert("createButton");
        var atrname = "xxxx";
        if (document.getElementById(atrname ) != null) {
        var fieldId = "field" + atrname ;

            var elementId = document.getElementById(atrname + "_d");
            var div = document.createElement("div");
            div.style.width = "20%";
            div.style.textAlign = "right";
            div.style.display = "inline";

            childDiv = elementId.getElementsByTagName('div')[0]
            childDiv.style.display = "none";

            elementId.appendChild(div, elementId );
            div.innerHTML = '<button id="' + fieldId + '"  type="button" style="margin-left: 4px; width: 50%;" >CRM Save Button</button>';
            document.getElementById(atrname).style.width = "80%";
            document.getElementById(fieldId ).onclick = function () { OnClickFunction(); };

    }
}

function OnClickFunction() {

    alert("clicked!");
}

Solution

  • With the introduction of turbo forms, things have changed a bit. If you want to access DOM, use document's parent element.

    function createButton() {
    var atrname = 'foobar';
    if (window.parent.document.getElementById(atrname) != null) {
        var fieldId = 'field' + atrname;
        var elementId = window.parent.document.getElementById(atrname + '_d');
        var div = window.parent.document.createElement('div');
        div.style.width = '20%';
        div.style.textAlign = 'right';
        div.style.display = 'inline';
    
        var childDiv = elementId.getElementsByTagName('div')[0];
        childDiv.style.display = 'none';
    
        elementId.appendChild(div, elementId);
        div.innerHTML = '<button id="' + fieldId + '"  type="button" style="margin-left: 4px; width: 50%;" >CRM Save Button</button>';
        window.parent.document.getElementById(atrname).style.width = '80%';
        window.parent.document.getElementById(fieldId).onclick = function () { OnClickFunction(); };
    
        }
    }