You can use word splitting and some regex to do that. This could give you a starting point:
- Get the cursor position.
- Get the text at that cursor position
- Match only alphabets out of that text (attributes would be alphabets).
Demo: http://jsfiddle.net/abhitalks/stepB/1/
However, this will work only if the value of the attribute value is empty (as per your question). If not, you may look for another way to match, but the concept remains same.
Code:
// handle an event
$("textarea").bind("click", function() {
var $input = $(this), // your textarea
text = $input.val(), // the entire text of the textarea
sel = this.selectionStart, // cursor position
word = findWord(text, sel), // get the specific word at cursor position
tag = word.match(/[A-z]+/); // match only alphabets from that word
$("#result").text(tag);
});
// function to find the word at specific position
function findWord(text, position){
var words = text.split(' '), // split at spaces into array of words
offset = 0, // track characters traversed
i; // index counter
for(i=0; i < words.length; i++){
offset += words[i].length + 1; // keep character count
if (offset > position) break; // if next count exceeds position,
} // we found the word at current index
return words[i];
}
Hope that helps.
Note: selectionStart
works from IE9 onwards. It is not supported in IE < 9. If you are looking to support IE.Legacy, then please have a look at the link proposed by @Esko in the comments below.