Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Maintaining whitespace from html to textarea and back

I've been trying to figure out how to maintain the whitespace and line breaks from html to textarea and back again. I'm creating a form that needs to be editable. I haven't been able to maintain the white space when I switch the html text to a textarea form to be able to edit. This is the code I've been working with so far:

//editing individual posts
    $('button.edit-post').on('click', function() {
        var $post = $('.post-body .post-text').text();
        var $editableText = $('<form id="editable-form"><textarea rows="20" id="editable-text"></textarea><button type="submit" class="submit-edit">Update</button>');
        $('.post-body .post-text').html($editableText);
        var $editableTextValue = $('#editable-text');
        $editableTextValue.val($post.replace('<p>', /\n\r?/g));
        $editableTextValue.focus();

    $('#editable-form').on('submit', function(e){
        e.preventDefault();
        var editedText = $editableTextValue.val().replace(/\n\r?/g, '<p>');
        $('.post-body .post-text').html('<p>' + editedText + '</p>');
    });
    });

Any help would be very much appreciated!