简体   繁体   中英

Create list html from selected text in Textarea

I have found various examples of using jquery to wrap selected text from a textarea in html tags, but I would like to adapt this slightly to create a list when multiple lines of text are selected.

Currently the code below wraps the whole selection in the list tags but I would also like to replace all the carriage returns with the closing and opening tags for list items - so each line in the text area is a new list item.

I think one of the problems might be that the .val function reads the text area as a single line.

jquery:

function listText(elementID, openTag, closeTag) {
    var textArea = $('#' + elementID);
    var len = textArea.val().length;
    var start = textArea[0].selectionStart;
    var end = textArea[0].selectionEnd;
    var selectedText = textArea.val().substring(start, end);
    var replacement = openTag + selectedText + closeTag;
    textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}

$(document).ready(function () {
    $("#BoldIt").click( function() {
        listText("markItUp", "<ul><li>", "</li></ul>");
    });
});

body:

<textarea id="markItUp" cols="80" rows="20"></textarea>

<br />

<input type="button" value="Bold" id="BoldIt" />

split your text like this:

function listText(elementID, openTag, closeTag) {
    var textArea = $('#' + elementID);
    var s = "\n";
    var len = textArea.val().length;
    var start = textArea[0].selectionStart;
    var end = textArea[0].selectionEnd;
    var selectedText = textArea.val().substring(start, end);
    var replacement = "";

    var rows = selectedText.substring(start, end).split(s);

    for(var i = 0; i < rows.length; i++) {
    replacement += openTag + rows[i] + closeTag + s;
    }

    textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}

$(document).ready(function () {
    $("#BoldIt").click( function() {
    listText("markItUp", "<ul><li>", "</li></ul>");
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM