Domanda

How do I check if the cursor is on an empty line inside a textarea?

I don't care about word wrapping. I care about lines that were created by hitting Enter.

$('textarea').on("change keyup", function() {
  if (cursor is on an empty line or the the line has just spaces) {
    console.log("empty");
  } else {
    console.log("has stuff");
  }
});

For example:

This would log "has stuff"

The line above would log "empty" and this line would log "has stuff"

È stato utile?

Soluzione

The following should work, but won't in older versions of IE.

// on(..., function() {
if( this.value.substr(0,this.selectionStart).match(/(?:^|\r?\n\s*)$/)
 && this.value.substr(this.selectionStart).match(/^(?:\s*\r?\n|$)/)) {
    console.log("empty");
}

EDIT search now explicitly looks for a newline, with further whitespace optional.

Altri suggerimenti

Another solution would be:

function is_cursor_on_empty_line(textarea)
{
    // line where cursor is now
    var line_number = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
    
    // split all lines of the textarea
    var lines = textarea.value.split("\n");

    // current line is empty or not
    return (lines[line_number-1] == '');
}

Example usage with Jquery:

var textarea = $('textarea');

if (is_cursor_on_empty_line(textarea[0]))
{
   // ...
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top