I'd like to store selected text in a variable and then delete the selected text by pressing a button. Preferably with jquery but I don't mind basic javascript.
Thanks in advance.
UPDATE:
Thanks George, I've tried the example that you pointed to stripping down the code to what I need but I can't get it to work on click for the button. It only works if I change #addchapter to textarea . Any idea whats wrong with my code? Thanks.
<html>
<head>
<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script type="text/javascript" src="jquery-fieldselection.js"></script>
<script type="text/javascript"><!--//--><![CDATA[//><!--
$(document).ready(function(){
$('#addchapter').click(update);
});
function update(e) {
var range = $(this).getSelection();
$('#output').html(
"selected text:\n<span class=\"txt\">" + ((true) ? range.text.whitespace() : range.text) + "</span>\n\n"
);
}
String.prototype.whitespace = (function() {
if (!RegExp.escape) {
RegExp.escape = (function() {
var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ];
var sRE = new RegExp( '(\\' + specials.join('|\\') + ')', 'g' );
return function(text) { return text.replace(sRE, '\\$1') }
})();
}
var ws = { "\r\n": "¶", "\n": "¶", "\r": "¶", "\t": "»", " ": "·" };
return ($.browser.msie) ? function() {
var s = this;
$.each(ws, function(i){ s = s.replace(new RegExp(RegExp.escape(i), 'g'), this) });
return s;
} : function () {
var s = this;
$.each(ws, function(i){ s = s.replace(new RegExp(RegExp.escape(i), 'g'), this + "\u200b") });
return s;
}
})();
//--><!]]>
</script>
</head>
<body>
<pre id="output"></pre>
<textarea id="area1" name="area1">textarea: foo bar baz</textarea>
<input type="button" value="add" id="addchapter">
</body>
</html>
UPDATE 2:
Ended up using this - http://plugins.jquery.com/project/a-tools