Search code examples
javascripthtmlmodal-dialoguser-input

How can I insert an input element dynamically into a modal?


I am working on a modal for user inputs. The available inputs depend on the button/case the user clicked, e.g. in one case the modal should offer a text input, and in another case, the modal should show a radio button. Therefore, I want to insert the input element of my modal dynamically with JavaScript.

Tested in a simple html page my code works, but not within the modal. Is there anything special about modals I missed? How can I adjust my code to get the input element?

<html lang="en">
<div id="workModal" class="w3-modal">
  <div class="w3-modal-content">
  <span class="close">&times;</span>
  <h4>Input</h4>
  <div id="mod_in"></div>
  </div>
</div>
</html>

<script>
var modal = document.getElementById("workModal");
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {modal.style.display = "none";};
window.onclick = function(event) {if (event.target == modal {modal.style.display = "none";}}

// here starts the filling of the modal:
function build_modal(info) {
    let element = document.getElementById("mod_in");
    let inElement = "";
    info.dataInputs.forEach(function (item){
        inElement = document.createElement("input");
        if (item.dataType.includes('string')){
            inElement.setAttribute("type", "text");
        }
        if (item.minOccurs > 0) {inElement.required = true}
        element.appendChild(inElement)
    });
    element.innerHTML = inElement;
    let modal = document.getElementById("workModal");
    modal.style.display = "block";
}
</script>

Instead of the input element, I get a [object HTMLInputElement] in my html code.


Solution

  • you have to use like below code for append new elements in html :

    $("button").click(function(){      //you can call your function after any events
      $("p").append("<b>Appended text</b>");  //you can append every element instead of <b> 
    });