JavaScript creating new line in HTML, onclick pastes values underneath one another

Issue

So i’ve looked around the website a lot but can’t seem to find the most basic way to create a new line in HTML through JavaScript. This would be activated by an onclick button that would copy the results from a table and post them in a separate div. Ideally, the “add line” button wouldn’t be replicated with each new line that was created. Rather, i’d have one button that each time was pressed, would take values from a table and make a text with all the values appear (not in another table). This concatenation of values wouldn’t be replaced once the new values are copied; the new values would be pasted underneath.

This is what i’ve been experimenting with:

HTML:

<table>
    <tr id="row4">
        <td>
            Result:
        </td>
        <td>
            <input type="text" placeholder="00" name="row4" class="row" id="row3_1"/>
        </td> 
        <td>
            <input type="text" placeholder="00" name="row4" class="row" id="row3_2"/>
        </td> 
        <td>
            <input type="text" placeholder="00" name="row4" class="row" id="row3_3"/>
        </td> 
        <td>
            <input type="text" placeholder="00" name="row4" class="row" id="row3_4"/>
        </td>
    </tr>
</table>

<input type="button" id="postToClipboard" onclick="postToClipboard()" value="Post results!">
<div id="clipboard"></div>

JavaScript:

function postToClipboard() {
    document.getElementById("clipboard").innerHTML = '<p>' + "Final Time =  " + (arrayRow3[0]  || 00) + ":" + (arrayRow3[1] || 00) + ":" + (arrayRow3[2] || 00) + ":" + (arrayRow3[3] || 00) + '</p>';
}

I learnt about join() recently but i’ll implement it in my next project instead.

Any help would be appreciated! Thanks in advance 🙂

Solution

In your JavaScript, use += to append, rather than = to overwrite:

function postToClipboard() {
    document.getElementById("clipboard").innerHTML += '<p>' + "Final Time =  " + (arrayRow3[0]  || 00) + ":" + (arrayRow3[1] || 00) + ":" + (arrayRow3[2] || 00) + ":" + (arrayRow3[3] || 00) + '</p>';
}

Answered By – Kenney

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.