Are we doing this right?

Hey guys,

My friend and i created an HTML page and we embedded an iframe within. We created some fields which will take in an image and texts as values using the upload image and input fields respectively. we are trying to get values of multiple input fields. We declared an array which takes it all in and we want to get those values from the innerHTML and send them to the parent HTML. We used the onmesaage() and postmessage() functions, we are not sure whether we’re correct in what we wrote codewise so we would like a hand. We are new to those two methods:

<script>
      // THE ARRAY SHOULD BE OUTSIDE THE FUNCTION SO IT DOESN'T GET REINITIATED. THE ARRAY KEEPS TRACK OF THE FIELDS AND WE CAN GET THEIR VALUES WHEN THE USER IS DONE
      window.addEventListener("message", handleMessage, false);

      function handleMessage(event) {
        if(event.origin !== "http://www.icy-tech.com"){
          return;

          event.source.postMessage("hi there yourself!  the secret response " +
                           "is: rheeeeet!", event.origin);
        }
      }
      window.onmessage = (event) => {
        if(event.data) {
            let receivedData = event.data;
            displayz.innerHTML = receivedData;
            displayclass.innerHTML = receivedData;
            document.getElementById("schLogo").innerHTML = receivedData;
        }
      };
      // creating a function to receive data from the innerHTML

      function button_clicked() {
          window.parent.postMessage(JSON.stringify(displayz.arr), "/");
          window.parent.postMessage(JSON.stringify(displayclass.classarr), "/");
          window.parent.postMessage(document.getElementById("schLogo").src, "/");
          sessionChanged();
          classChanged();
      }

     var arr = [];
      var displayz = document.getElementById("showTermsFields");
      //declaring variable for class
      function sessionChanged() {
        //REMOVE THE INITIAL FIELDS IN THE HTML
        for (i = 0; i < arr.length; i++) {
          let id = arr[i];
          document.getElementById(id).remove();
        }

        //SET THE ARRAY INTO AN EMPTY ARRAY
        arr = [];

        //FOR THE NUMBER OF TERMS ADD NEW FIELDS
        var terms = document.getElementById("terms_session").options
          .selectedIndex;
        for (i = 0; i < terms; i++) {
          //CREATE THE ELEMENT
          var input = document.createElement("INPUT");
          //SET THE ID ATTRIBUTE OF THE ELEMENT
          let id = i.toString() + "term";
          input.setAttribute("id", id);
          input.placeholder = "Enter Term";

          //input.style.margin="0.2em";
          input.style.backgroundColor = "#e6e6e6";
          input.style.width = "50%";
          input.style.borderRadius = "0.6em";
          input.style.borderWidth = ".06em";
          input.style.display = "block";
          input.style.padding = "0.4em";
          input.style.margin = "0.6em";
          input.style.marginLeft = "auto";
          input.style.marginRight = "auto";
          input.style.textAlign = "center";
          input.style.width = "28em";
          //ADD THE FIELD TO THE BODY
          displayz.appendChild(input);
          // ADD THE ID TO THE ARRAY
          arr.push(id);
          input.onchange = function () {
            termfunction(id);
          };
          console.log(arr);
        }
      }
      function termfunction(id) {
        let d = document.getElementById(id.toString());
        var termdata = d.value;
        console.log(termdata);
      }

      // var dataarr = [];
      var classarr = [];
      var displayclass = document.getElementById("showClassesFields");
      function classChanged() {
        for (n = 0; n < classarr.length; n++) {
          let id = classarr[n];
          document.getElementById(id).remove();
        }
        //SET THE ARRAY INTO AN EMPTY ARRAY
        classarr = [];

        //FOR THE NUMBER OF TERMS ADD NEW FIELDS
        var term = document.getElementById("number_class").options
          .selectedIndex;
        for (n = 0; n < term; n++) {
          //CREATE THE ELEMENT
          var input = document.createElement("INPUT");
          //SET THE ID ATTRIBUTE OF THE ELEMENT
          //  datad = id
          let id = n.toString() + "class";
          input.setAttribute("id", id);
          input.placeholder = "Enter Class";

          input.style.backgroundColor = "#d9d9d9";
          input.style.borderRadius = "0.6em";
          input.style.borderWidth = ".06em";
          //input.style.borderLeft = 'none';
          input.style.outline = "none";
          input.style.margin = "0.6em";
          input.style.display = "block";
          input.style.padding = "0.3em";
          input.style.marginLeft = "auto";
          input.style.marginRight = "auto";
          // input.style.= 'center';
          input.style.textAlign = "center";
          input.style.width = "50%";
          //ADD THE FIELD TO THE BODY
          displayclass.appendChild(input);
          // ADD THE ID TO THE ARRAY
          classarr.push(id);
          input.onchange = function () {
            classfunction(id);
          };
          //classarr.forEach(classfunction);
        }
        for (n = 0; n < classarr.length; n++) {
          let id = classarr[n];
          //        document.getElementById(n).remove()
          console.log(n);
          //console.log(n)
        }
      }

      var addClassSub = document.getElementById("classSub");
      function classfunction(id) {
        let d = document.getElementById(id.toString());
        var classdata = d.value;
        classarr.push(classdata);
        console.log(classarr);
      }
      var n = -1;
      var len = classarr.length;
      //console.log = len;
      //document.getElementById('classSub').innerHTML = classarr[0] + ':';
      function show() {
        n += 1;
        var f = classarr[n];
        if (f !== undefined) {
          console.log(f);
          document.getElementById("classSub").innerHTML = "for " + f + " :";
        } else {
          document.getElementById("notification").innerHTML =
            "cant perform this operation";
        }
      }
      function add() {
        var input = document.createElement("input");
        var pAdd = document.getElementById("input");
        pAdd.appendChild(input);
        input.style.placeholder = "Enter Subject";
        input.style.backgroundColor = "#d9d9d9";
        input.style.borderRadius = "0.6em";
        input.style.borderWidth = ".06em";
        //input.style.borderLeft = 'none';
        input.style.outline = "none";
        input.style.margin = "0.6em";
        input.style.display = "block";
        input.style.padding = "0.3em";
        input.style.marginLeft = "auto";
        input.style.marginRight = "auto";
        input.style.textAlign = "center";
        input.style.width = "50%";
      }
    </script>

We are particularly afraid we are not getting it right with the onmessage() and postmessage() functions. A little help if our fears are true.

Can you please put together some sample HTML code, so that we can use the JavaScript code on it in a way that it’s expected to work?

Just having a scan and I think this block and another similar one further down in your code, could be addressed. You could set this as a class definition in CSS instead

.my-class  {
  background-color: #d9d9d9;
  display: none;
  margin: .6em auto;
  padding: .3em
  outline: 0; // frowned upon
  .
  .
}

and then something like this in your JS
input.classList.add('my-class')

Sorry for the late response. The full code is written below:

<html lang="en">
  <head>
    <style>
      * {
          box-sizing: border-box;
      }

      body {
          margin: 0;
          padding: 0;
          font-size: 16px;
          font-family: arial;
          line-height: 1.6;
      }

      .container {
          max-width: 800px;
          margin: 50 auto;

      }

      .tab_triger ul {
          margin: 0;
          padding: 0;
          list-style: none;
          display: flex;
      }

      .tab_triger ul li label {
          position: relative;
          display: block;
          padding: 8px 15px;
          cursor: pointer;
          min-width: 100px;
          background: #e6e6e6;
          text-align: center;
          font-weight: 700;
          text-transform: uppercase;
          border-radius: 8px 8px 0 0;
      }

      .tab_triger ul li:nth-child(1) label {
          background: #f0f0f0;]
      }

      .tab_triger ul li:nth-child(2) label {
          background: #e6e6e6;
      }

      .tab_triger ul li:nth-child(3) label {
          background: #d9d9d9;
      }

      .tab_triger ul li:nth-child(4) label {
          background: #ccc;
      }

      .tab_container_wrap .scroll {
          position: absolute;
          width: 0;
          height: 0;
          margin: 0;
          z-index: -100;
          top: -10000px;

      }

      .tab_container_wrap input:checked+.tab_content_box {
          display: block;
      }

      .tab_content_box {
          background: #f0f0f0;
          padding: 20px;
          display: none;

      }

      .tab_content_box:nth-of-type(1) {
          background: #f0f0f0;


      }

      .tab_content_box:nth-of-type(2) {
          background: #e6e6e6;
      }

      .tab_content_box:nth-of-type(3) {
          background: #d9d9d9;
      }

      .tab_content_box:nth-of-type(4) {
          background: #ccc;
      }

      .tab_content_box h2 {
          margin: 0 0 20px;
      }
    </style>
    <link
      href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
      rel="stylesheet"
      integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
      crossorigin="anonymous"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <!-- Script to handle sending data from this html page-->
    <script type="text/javascript">
      function init() {
        // When a message is received from the HTML page
        windows.onmessage = (event) => {
          if (event.data) {
            document.getElementById("terms_session").innerHTML = event.data;
          }
        };
      }
    </script>
  </head>

  <body>
    <div class="container">
      <div class="tab_triger">
        <ul>
          <li><label for="School_Logo">School Logo</label></li>
          <li><label for="Sessions">Terms</label></li>
          <li><label for="Classes">Classes</label></li>
          <li><label for="Subject">Subject</label></li>
        </ul>
      </div>
      <!--code for first tab-->
      <div class="tab_container_wrap">
        <input type="radio" checked id="School_Logo" name="1" class="scroll" />
        <div class="tab_content_box" id="box1">
          <h2>School Logo</h2>
          <input
            type="image"
            src="http://www.nretnil.com/avatar/LawrenceEzekielAmos.png"
            alt="school_logo"
            style="
              width: 10em;
              height: 10em;
              border: 2px solid black;
              border-radius: 50%;
            "
            id="schLogo"
          />
          <input type="file" name="logo" onchange="document.getElementById('schLogo').src = window.URL.createObjectURL(this.files[0])"><br /><br />

          <button
            id="nxt"
            style="
              float: right;
              margin-bottom: 2em;
              width: 10em;
              height: 3em;
              font-weight: 700;
            "
            class="next"
          >
            Next</button
          ><br /><br />
        </div>

        <!--code for second tab-->
        <input type="radio" id="Sessions" name="1" class="scroll" />
        <div class="tab_content_box" id="box2">
          <form action="">
            <h2>Choose Terms:</h2>
            <div id="school_operation">
              <select
                name="terms_session"
                id="terms_session"
                style="
                  background-color: #e6e6e6;
                  margin-left: 11.8em;
                  outline: none;
                  border-radius: 0.7em;
                  font-size: 1em;
                  font-weight: 200;
                  padding: 0.4em;
                  position: block;
                  width: 50%;
                "
                onchange="sessionChanged()"
              >
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="others">Others</option>
              </select>
              <p
                id="showTermsFields"
                style="padding: 0.4em; margin-top: 2em;"
              ></p>
              <br /><br />
            </div>
          </form>
          <button
            id="prev"
            style="
              float: left;
              margin-bottom: 2em;
              width: 10em;
              height: 3em;
              font-weight: 700;
            "
            class="prev"
          >
            Previous
          </button>
          <button
            id="nxt"
            style="
              float: right;
              margin-bottom: 2em;
              width: 10em;
              height: 3em;
              font-weight: 700;
            "
            class="next"
          >
            Next</button
          ><br /><br />
        </div>

        <input type="radio" id="Classes" name="1" class="scroll" />
        <div class="tab_content_box" id="box3" style="width: 100%;">
          <form action="" style="width: 100%;">
            <h2>Numbers of Classes:</h2>
            <div id="school_operation">
              <select
                name="number_class"
                id="number_class"
                style="
                  background-color: #d9d9d9;
                  outline: none;
                  border-radius: 0.7em;
                  font-size: 1em;
                  font-weight: 200;
                  align-items: center;
                  margin-left: 11.84em;
                  margin-right: auto;
                  width: 50%;
                  padding: 0.4em;
                "
                onchange="classChanged()"
              >
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
                <option value="6">6</option>
                <option value="7">7</option>
                <option value="8">8</option>
                <option value="9">9</option>
                <option value="10">10</option>
                <option value="11">11</option>
                <option value="12">12</option>
                <option value="13">13</option>
                <option value="14">14</option>
                <option value="15">15</option>
                <option value="16">16</option>
                <option value="others">Others</option>
              </select>
              <p
                id="showClassesFields"
                style="padding: 0.4em; margin-top: 2em;"
              ></p>
              <br /><br />
            </div>
          </form>
          <button
            id="prev"
            style="
              float: left;
              margin-bottom: 2em;
              width: 10em;
              height: 3em;
              font-weight: 700;
            "
            class="prev"
          >
            Previous
          </button>
          <button
            id="nxt"
            style="
              float: right;
              margin-bottom: 2em;
              width: 10em;
              height: 3em;
              font-weight: 700;
            "
            class="next"
          >
            Next</button
          ><br /><br />
        </div>

        <input type="radio" id="Subject" name="1" class="scroll" />
        <div class="tab_content_box" id="box4">
          <h2>Subjects</h2>
          <p
            id="classSub"
            style="
              background-color: rgb(0, 0, 0, 0.2);
              width: 25%;
              padding: 1em;
              text-align: left;
              font-weight: 1000;
              text-transform: uppercase;
            "
          ></p>
          <p id="notification" style="color: red; font-size: 0.8em;"></p>
          <form action="" style="right: 0px; width: 100%;">
            <p id="input"></p>
            <p style="padding-left: 45em; cursor: pointer;" onclick="add()">
              <i
                class="fa fa fa-plus-circle"
                aria-hidden="true"
                title="add subject"
              ></i>
            </p>
          </form>

          <button
            onclick="show()"
            style="
              background-color: blue;
              outline: none;
              border: none;
              font-weight: 700;
              padding: 0.5em;
              border-radius: 2em;
              color: whitesmoke;
            "
          >
            Next Class
          </button>
          <p id="show"></p>
          <button
            id="prev"
            style="
              float: left;
              margin-bottom: 2em;
              width: 10em;
              height: 3em;
              font-weight: 700;
            "
            class="prev"
          >
            Previous
          </button>
          <button
            id="finish"
            style="
              float: right;
              margin-bottom: 2em;
              width: 10em;
              height: 3em;
              font-weight: 700;
            "
            onclick="button_clicked()"
          >
            Finish</button
          ><br /><br />
        </div>
      </div>
    </div>
    <script>
      // script to move around the next and prev button
      $(".next").click(function () {
        $("input[name=1]:checked").nextAll("input:enabled").first().click();
      });
      $(".prev").click(function () {
        $("input[name=1]:checked").prevAll("input:enabled").first().click();
      });
    </script>
    <script>
      // THE ARRAY SHOULD BE OUTSIDE THE FUNCTION SO IT DOESN'T GET REINITIATED. THE ARRAY KEEPS TRACK OF THE FIELDS AND WE CAN GET THEIR VALUES WHEN THE USER IS DONE
      window.addEventListener("message", handleMessage, false);

      function handleMessage(event) {
        if(event.origin !== "http://www.icy-tech.com"){
          return;

          event.source.postMessage("hi there yourself!  the secret response " +
                           "is: rheeeeet!", event.origin);
        }
      }
      window.onmessage = (event) => {
        if(event.data) {
            let receivedData = event.data;
            displayz.innerHTML = receivedData;
            displayclass.innerHTML = receivedData;
            document.getElementById("schLogo").innerHTML = receivedData;
        }
      };
      // creating a function to receive data from the innerHTML

      function button_clicked() {
          window.parent.postMessage(JSON.stringify(displayz.arr), "/");
          window.parent.postMessage(JSON.stringify(displayclass.classarr), "/");
          window.parent.postMessage(document.getElementById("schLogo").src, "/");
          sessionChanged();
          classChanged();
      }

     var arr = [];
      var displayz = document.getElementById("showTermsFields");
      //declaring variable for class
      function sessionChanged() {
        //REMOVE THE INITIAL FIELDS IN THE HTML
        for (i = 0; i < arr.length; i++) {
          let id = arr[i];
          document.getElementById(id).remove();
        }

        //SET THE ARRAY INTO AN EMPTY ARRAY
        arr = [];

        //FOR THE NUMBER OF TERMS ADD NEW FIELDS
        var terms = document.getElementById("terms_session").options
          .selectedIndex;
        for (i = 0; i < terms; i++) {
          //CREATE THE ELEMENT
          var input = document.createElement("INPUT");
          //SET THE ID ATTRIBUTE OF THE ELEMENT
          let id = i.toString() + "term";
          input.setAttribute("id", id);
          input.placeholder = "Enter Term";

          //input.style.margin="0.2em";
          input.style.backgroundColor = "#e6e6e6";
          input.style.width = "50%";
          input.style.borderRadius = "0.6em";
          input.style.borderWidth = ".06em";
          input.style.display = "block";
          input.style.padding = "0.4em";
          input.style.margin = "0.6em";
          input.style.marginLeft = "auto";
          input.style.marginRight = "auto";
          input.style.textAlign = "center";
          input.style.width = "28em";
          //ADD THE FIELD TO THE BODY
          displayz.appendChild(input);
          // ADD THE ID TO THE ARRAY
          arr.push(id);
          input.onchange = function () {
            termfunction(id);
          };
          console.log(arr);
        }
      }
      function termfunction(id) {
        let d = document.getElementById(id.toString());
        var termdata = d.value;
        console.log(termdata);
      }

      // var dataarr = [];
      var classarr = [];
      var displayclass = document.getElementById("showClassesFields");
      function classChanged() {
        for (n = 0; n < classarr.length; n++) {
          let id = classarr[n];
          document.getElementById(id).remove();
        }
        //SET THE ARRAY INTO AN EMPTY ARRAY
        classarr = [];

        //FOR THE NUMBER OF TERMS ADD NEW FIELDS
        var term = document.getElementById("number_class").options
          .selectedIndex;
        for (n = 0; n < term; n++) {
          //CREATE THE ELEMENT
          var input = document.createElement("INPUT");
          //SET THE ID ATTRIBUTE OF THE ELEMENT
          //  datad = id
          let id = n.toString() + "class";
          input.setAttribute("id", id);
          input.placeholder = "Enter Class";

          input.style.backgroundColor = "#d9d9d9";
          input.style.borderRadius = "0.6em";
          input.style.borderWidth = ".06em";
          //input.style.borderLeft = 'none';
          input.style.outline = "none";
          input.style.margin = "0.6em";
          input.style.display = "block";
          input.style.padding = "0.3em";
          input.style.marginLeft = "auto";
          input.style.marginRight = "auto";
          // input.style.= 'center';
          input.style.textAlign = "center";
          input.style.width = "50%";
          //ADD THE FIELD TO THE BODY
          displayclass.appendChild(input);
          // ADD THE ID TO THE ARRAY
          classarr.push(id);
          input.onchange = function () {
            classfunction(id);
          };
          //classarr.forEach(classfunction);
        }
        for (n = 0; n < classarr.length; n++) {
          let id = classarr[n];
          //        document.getElementById(n).remove()
          console.log(n);
          //console.log(n)
        }
      }

      var addClassSub = document.getElementById("classSub");
      function classfunction(id) {
        let d = document.getElementById(id.toString());
        var classdata = d.value;
        classarr.push(classdata);
        console.log(classarr);
      }
      var n = -1;
      var len = classarr.length;
      //console.log = len;
      //document.getElementById('classSub').innerHTML = classarr[0] + ':';
      function show() {
        n += 1;
        var f = classarr[n];
        if (f !== undefined) {
          console.log(f);
          document.getElementById("classSub").innerHTML = "for " + f + " :";
        } else {
          document.getElementById("notification").innerHTML =
            "cant perform this operation";
        }
      }
      function add() {
        var input = document.createElement("input");
        var pAdd = document.getElementById("input");
        pAdd.appendChild(input);
        input.style.placeholder = "Enter Subject";
        input.style.backgroundColor = "#d9d9d9";
        input.style.borderRadius = "0.6em";
        input.style.borderWidth = ".06em";
        //input.style.borderLeft = 'none';
        input.style.outline = "none";
        input.style.margin = "0.6em";
        input.style.display = "block";
        input.style.padding = "0.3em";
        input.style.marginLeft = "auto";
        input.style.marginRight = "auto";
        input.style.textAlign = "center";
        input.style.width = "50%";
      }
    </script>
  </body>
</html>

Ok. i will try that for the CSS part.