Reputation: 820
I'm trying to highilght a string/text in textarea and then wrap it around a custom tag.
I can easily now get the highlighted text and I can wrap it around the tag and alert() it but I cannot replace it inside the textarea.
This is my working FIDDLE(https://jsfiddle.net/dftLu6ax/)
And this is my Javascript/jQuery code:
$('#showSelected').on('click', function(){
function getInputSelection(elem){
if(typeof elem != "undefined"){
s=elem[0].selectionStart;
e=elem[0].selectionEnd;
return elem.val().substring(s, e);
}else{
return '';
}
}
var text = getInputSelection($("#details"));
var link = prompt("Please enter your URL", "");
if (link != null) {
var str = document.getElementById("details").value;
var res = str.replace(text, "<a onclick='somevariable goes here' href=''>"+text+"</a>");
alert(res);
/*document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";*/
}
});
and my simple HTML:
<input type="button" id="showSelected" value="Insert Link">
<textarea class="form-control" rows="5" id="details" name="details"></textarea>
Could someone please advise on this?
Thanks in advance.
Upvotes: 1
Views: 452
Reputation: 42044
Because you get the text inside the textarea with:
document.getElementById("details").value
You may use the same to set the updated value:
function getInputSelection(elem){
if(typeof elem != "undefined"){
s=elem[0].selectionStart;
e=elem[0].selectionEnd;
return elem.val().substring(s, e);
}else{
return '';
}
}
$(function () {
$('#showSelected').on('click', function(){
var text = getInputSelection($("#details"));
var link = prompt("Please enter your URL", "");
if (link != null) {
var str = document.getElementById("details").value;
var res = str.replace(text, "<a onclick='somevariable goes here' href=''>"+text+"</a>");
//THIS LINE
document.getElementById("details").value = res;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="showSelected" value="Insert Link">
<textarea class="form-control" rows="5" id="details" name="details"></textarea>
Upvotes: 3
Reputation: 1324
Use $("#details").val(res)
for that
$('#showSelected').on('click', function(){
function getInputSelection(elem){
if(typeof elem != "undefined"){
s=elem[0].selectionStart;
e=elem[0].selectionEnd;
return elem.val().substring(s, e);
}else{
return '';
}
}
var text = getInputSelection($("#details"));
var link = prompt("Please enter your URL", "");
if (link != null) {
var str = document.getElementById("details").value;
var res = str.replace(text, "<a onclick='somevariable goes here' href=''>"+text+"</a>");
$("#details").val(res);
/*document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";*/
}
});
Fiddle: https://jsfiddle.net/dftLu6ax/3/
Upvotes: 2