Translate

Tuesday, April 3, 2012

Jquery add text to multiline textbox with line breaks

If you select text from a multiline textbox using .text() then the line breaks get lost. Instead of text() use .val() to preserve line breaks in the textbox.


Example


Save the text below with a .htm extension. When you open the .htm file in a browser and click the button, you can see text being added with line breaks (in new line)

<script src="http://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {

        $("#btn1").click(function () {
            changeTheText();
        });


        function changeTheText() {
            var x = $('#multiLinetxtBox').val() + '\r\n' + new Date();


            $(' #multiLinetxtBox ').val(x);

        };

    });
</script>
<html>
<body>

<textarea style="height: 500px;"  id="multiLinetxtBox" cols="20" rows="2">
line 1
line 2
line 3
</textarea>

<input id="btn1" type="button" value="ClickMe" />
</body>
</html>

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator