Home > OS >  How to display multiple words from the same submission form?
How to display multiple words from the same submission form?

Time:10-24

I am trying to make a submission form that can be used multiple times, which displays the words that are submitted next to each other. So far I have been able to do the submission form and when the submit button is pressed, the word is displayed, but when the submission form is filled with another word and re-submitted, it takes over the previous word that was displayed. Here is my code:

function showTag(){
    document.getElementById('display').innerHTML = 
          document.getElementById("user_input").value;
}
<form>
    <input type="text" name="message" id="user_input">
</form>
<input type="submit" onclick="showTag()">
<p><span class="tag is-info" style="background-color:#33475b;color:white;" id='display'></span></p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I have looked around but all I have been able to find are "multiple submit buttons" solutions, which is not what I am looking for. Any help would be very appreciated.

CodePudding user response:

For that you need to have a intermediary variable that can store all the values:

    const arr = [];

    function showTag() {
        arr.push(document.getElementById("user_input").value)
        document.getElementById('display').innerHTML = arr.join(' ')
    }
<form>
    <input type="text" name="message" id="user_input">
</form>
<input type="submit" onclick="showTag()">
<p><span class="tag is-info" style="background-color:#33475b;color:white;" id='display'></span></p>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Edit: For each submission from the user become a new element, you will still need the array to store the data from the user, but instead of joining the array, you must create a new element with the last item from the array:

    const arr = [];

    function showTag(e) {

        arr.push(document.getElementById("user_input").value)
        phrase = document.createElement('p');
        phrase.innerHTML = arr.at(-1);
        document.getElementById('phrases').appendChild(phrase);


    }
    p {
        width: fit-content;
        background-color: #33475b;
        color: white;
    }
<form>
    <input type="text" name="message" id="user_input">
</form>
<input type="submit" onclick="showTag()">
<div id='phrases'></div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related