2

I am trying to add checkbox which says: "Enable Snap: []". If user click on that checkbox i want to check that checkbox is checked or not. But i am getting error like: document.getElementById(...) is null.

Below is the code:

instance.setHeaderItems(header => {
    header.getHeader('toolbarGroup-Annotate').unshift({
        type: 'customElement',
        render: function() {
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.name = 'snap-to-grid';
            checkbox.value = '1';
            checkbox.id = 'snap-to-grid';
            checkbox.onclick = function(evt) {
                alert(document.getElementById('snap-to-grid').checked);
            };
            return checkbox;
        }
    });
});

So is there a way to know that checkbox is checked or not? Also how can i add some text before checkbox?

DS9
  • 2,995
  • 4
  • 52
  • 102

1 Answers1

3

WebViewer is ran inside iframe on your page. When we render these custom buttons they are also inside that iframe. To access element in your case you first need to get the document of the iframe. This should work for you

instance.setHeaderItems(header => {
    header.getHeader('toolbarGroup-Annotate').unshift({
      type: 'customElement',
      render: function() {
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.name = 'snap-to-grid';
        checkbox.value = '1';
        checkbox.id = 'snap-to-grid';
        checkbox.onclick = function(evt) {
          alert(instance.iframeWindow.document.getElementById('snap-to-grid').checked);
        };
        return checkbox;
      }
    });
  });
  • That checkbox get reset (i.e. unchecked) if i click on "Tools" option which has pencil icon. So is there a any event which i can use when user click on "Tools" option so using global variable i can check the checkbox again? – DS9 Nov 24 '20 at 10:39
  • 2
    We call this render function every time our component refresh. As you are controlling rendering of that checkbox you can keep your checkbox state in your own code, meaning in this case outside of instance.setHeaderItems() function – Jussi Nieminen Nov 25 '20 at 16:45