0

I have an iframe element in my html page. src attribute of the iframe varies dynamically based on user selected values [SHAP,LIME]. User values are shown as drop down with id explanationType.

However I need to add an additional iframe into the html page if user selects SHAP but not when user selects LIME. How to achieve this?

HTML

<iframe id="js-iframe" src="https://www.youtube.com/watch?v=hVCYwwFwGEE&list=RDhVCYwwFwGEE&index=1" width="100%" height="80%" frameborder="0">
  <p>Your browser does not support iframes.</p>
</iframe>

JS

// Update iframe
var explanationTypeOptions = document.getElementById("explanationType");

var explanationURL = explanationTypeOptions.options[explanationTypeOptions.selectedIndex].getAttribute('kibanaurl');

if(explanationURL) {
  var iframeDOMHandler = document.getElementById("js-iframe");
  iframeDOMHandler.setAttribute('src', explanationURL);
}
V. Sambor
  • 12,361
  • 6
  • 46
  • 65
Anandraj
  • 45
  • 1
  • 7
  • 1
    Possible duplicate of [Creating an IFRAME using JavaScript](https://stackoverflow.com/questions/8726455/creating-an-iframe-using-javascript/8726513) (Can't vote close because I've retracted, someone do please). – Jorge Fuentes González Aug 31 '19 at 09:36

1 Answers1

0

When you change your select option you can listen to onchange event and do your logic there.

The code should look somehting like this:

var $sel = document.getElementById('explanationType');

$sel.onchange = function (e) {
    var selectedValue = e.target.value;
    var $option = e.target.options[e.target.selectedIndex];
    var url = $option.getAttribute('kibanaurl');

    if (url) {
        document.getElementById("js-iframe").setAttribute('src', url);
    }

    if (selectedValue === 'SHAP') {
        var $newIFrame = document.createElement("iframe");
        $newIFrame.setAttribute("src", "http://example.com");
        $newIFrame.style.width = "300px";
        $newIFrame.style.height = "300px";
        document.body.appendChild($newIFrame);
    }
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Test</title>
</head>
<body>
  
  <select id="explanationType">
    <option value="SHAP" kibanaurl="https://image.shutterstock.com/image-vector/example-sign-paper-origami-speech-260nw-1164503347.jpg">SHAP</option>
    <option value="LIME" kibanaurl="https://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg">LIME</option>
  </select>

  <iframe id="js-iframe" src="https://www.youtube.com/watch?v=hVCYwwFwGEE&list=RDhVCYwwFwGEE&index=1" width="100%" height="80%" frameborder="0">
    <p>Your browser does not support iframes.</p>
  </iframe>
  
</body>
</html>
V. Sambor
  • 12,361
  • 6
  • 46
  • 65