1

I currently have a system that sort of works. I want to add <br /> when the user hits enter.

At present the way it works is to grab the current contents of the textarea, append <br /> onto it and then output the whole lot back. So this works but only adds the <br /> to the end of the content.

    $("#postcontent").keypress(function(e) {
    // If enter key pressed
    if(e.which == 13) {
        var currentHTML = document.getElementById("postcontent").value;
        var currentHTML = currentHTML + "\n<br /><br />"
        document.getElementById("postcontent").value = currentHTML;
    }
});

Here's a JSfiddle of the above in action I'm aware the current solution wouldn't work for adding in a <br /> tag at the current cursor location.

I was thinking something like this but not sure how to handle it.

    $("#postcontent").keypress(function(e) {
    // If enter key pressed
    if(e.which == 13) {
        // Find the location of the cursor
        // Grab all the content BEFORE the cursor and store in var contentBefore
        // Grab all the content AFTER the cursor and store in var contentAfter
        document.getElementById("postcontent").value = contentBefore + "<br /><br />"  + contentAfter;
    }
});

Not sure if I'm going about it the complete wrong way, so please feel free to offer alternative solutions or help me work out parts of the pseudo code above?

Francesca
  • 26,842
  • 28
  • 90
  • 153
  • 1
    I think you are looking for "caret position in text area" , maybe this will help http://stackoverflow.com/questions/263743/caret-position-in-textarea-in-characters-from-the-start – Chris Oct 17 '14 at 13:40

2 Answers2

1

Here's jQuery way:

$(document).ready(function(){
    $("#postcontent").keypress(function(e) {
    if(e.which == 13) {
        //var currentHTML = document.getElementById("postcontent").value;
        //var currentHTML = currentHTML + "\n<br /><br />"
        //document.getElementById("postcontent").value = currentHTML;

    var cursorPos = $('#postcontent').prop('selectionStart'),
    v = $('#postcontent').val(),
    textBefore = v.substring(0,  cursorPos ),
    textAfter  = v.substring( cursorPos, v.length );
    $('#postcontent').val( textBefore+ "<br />" +textAfter );


    }
});
});

http://jsfiddle.net/o9jaatak/1/

Chris
  • 3,405
  • 4
  • 29
  • 34
0

Tim Down has an answer on this question:

How do I insert some text where the cursor is?

It should fit your needs exactly. Just call that as a part of your keypress handling.

Community
  • 1
  • 1