I have a textarea where when the user selects and presses enter I want it to change to something else. For example I have a textarea, when a user selects something like NY, I want those two letters to change to NY
I have something like:
$('textarea').html('I live in NY and it\'s a great place to live');
$(window).click(function(){
var selection = selectedText();
console.log(selection);
});
function selectedText() {
var ret = '';
if (window.getSelection){
ret = window.getSelection();
} else if (document.getSelection) {
ret = document.getSelection();
} else if (document.selection) {
ret = document.selection.createRange().text;
}
return ret;
}
I don't know where to check to see if it's from a textarea or from somewhere else, and I don't know how to change a specific part of a textarea's text
This might help you:
Finding selection start and end position in a textarea
Also i just tested this and it works (it returns the selected text, so you can modify it and assign the value back to the textarea
Ref: http://www.codingforums.com/showpost.php?p=235174&postcount=5
<script type="text/javascript">
<!--//
function selectedText(input){
if(document.selection && document.selection.createRange().text != ''){ // IS IE
alert(document.selection.createRange().text);
}
else{ // Not IE.. assume Mozilla?
var startPos = input.selectionStart;
var endPos = input.selectionEnd;
alert(input.value.substring(startPos, endPos))
}
}
//-->
</script>
</head>
<body>
<form name="reportForm">
<textarea name="report">this is a test</textarea>
<button onclick="selectedText(this.form.report)">Alert Selection</button>
</form>
There are a lot of cross browser nuances when it comes to text selection. There are several jQuery plugins trying to deal with this. I'd recommend using a-tools . I've used it in the past, and it works as advertised.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.