Search code examples
javascripthtmlfunctiongetelementbyid

Passing input to span field


I am trying to pass the input i have from an input to an span field. I use an api dropdown list with results. So if people click on an search result it get autofilled in (much like google). I want to pass this result to an span field I have in my page.

However I dont want an onclick event if people click on an result. Rather when people click out of the input field..

This is what I tried:

    <div>
        <input id="exercise-search" class="form-control" type="text" name="data">
    </div>
    <span id="namespan">Name</span>

And the simple script:

        <script>

            var name = document.getElementById("exercise-search").value;
            document.getElementById("namespan").textContent=name;

            function reload(){
                var container = document.getElementById("namespan");
                var content = container.innerHTML;
                container.innerHTML= content;
            }
        </script>

However I still have to manually refresh the page to see the result. How can i automate this?


Solution

  • Add a listener for the change event to the input field. This will be executed when the user edits the field and clicks out of it.

    document.getElementById("exercise-search").addEventListener("change", function() {
        var name = this.value;
        document.getElementById("namespan").textContent=name;
    });