JG7
JG7

Reputation: 371

Javascript Textbox Copy/Paste Loss of Newline

I have a Tampermonkey script that creates a list of values from checked checkboxes on a webpage. The box displays the data beautifully, each value on a new line below the other. However, I lose the newline characters when I copy and paste these values using Microsoft clipboard. Is there a way to adjust the script in order to allow preservation of the newline characters (\n)?

JavaScript:

var box = document.createElement( 'div' );
box.id = 'myAlertBox';

document.body.appendChild( box );

box.textContent = text + '\n';

var selectedQueries = document.querySelectorAll (query);

selectedQueries.forEach ( (chkBox) => {
    box.textContent += chkBox.title + '\n';
});

CSS:

#myAlertBox {
    font-size: small;
    background: white;
    border: 5px solid green;
    padding: 4px;
    position: absolute;
    top: 280px; right: 80px;
    max-width: 300px;
    white-space:pre-wrap;
}

Upvotes: 1

Views: 1144

Answers (2)

JG7
JG7

Reputation: 371

Thanks everyone! I simply changed textContent to innerHTML and used <br/> as the line breaks as suggested. You have all collectively saved me a lot of manual labor.

Working code:

function ParseCheckBoxes (query, text) {

    if (document.getElementById('myAlertBox') !== null) {
        document.getElementById("myAlertBox").outerHTML='';
    }

    var box = document.createElement( 'div' );
    box.id = 'myAlertBox';

    document.body.appendChild( box );

    box.innerHTML = text + '<br/>';

    var selectedQueries = document.querySelectorAll (query);

    selectedQueries.forEach ( (chkBox) => {
        box.innerHTML += chkBox.title + '<br/>';
    });
}

Upvotes: 1

Kalaikumar Thangasamy
Kalaikumar Thangasamy

Reputation: 564

HTML will not support \n because it will treated as white space. Use <br/> tag for line break.

var box = document.createElement( 'div' );
box.id = 'myAlertBox';

document.body.appendChild( box );

box.textContent = text + '<br/>';

var selectedQueries = document.querySelectorAll (query);

selectedQueries.forEach ( (chkBox) => {
    box.textContent += chkBox.title + '<br/>';
});

Upvotes: 0

Related Questions