2016-08-25 122 views
0

我試圖高亮textarea中的一個字符串/文本,然後將其包裹在自定義標記周圍。Javascript:替換文本區域中突出顯示的字符串?

我現在可以很容易地得到突出顯示的文本,並且我可以將它包裹在標記周圍並警告()它,但我無法在textarea內替換它。

這是我的工作FIDDLE(https://jsfiddle.net/dftLu6ax/

,這是我的Javascript/jQuery代碼:

$('#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?";*/ 
    } 

}); 

和我簡單的HTML:

<input type="button" id="showSelected" value="Insert Link"> 


    <textarea class="form-control" rows="5" id="details" name="details"></textarea> 

可能有人請告知本?

在此先感謝。

+0

試試這個'$(「#details」).val(res);'。這將取代textarea中選定的文本與你正在顯示的警報 – Akshay

+0

@Akshay,我不想用我剛纔突出顯示的文本替換textarea中的整個文本! – Jackson

回答

1

使用$("#details").val(res)

$('#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?";*/ 
    } 

}); 

小提琴:https://jsfiddle.net/dftLu6ax/3/

2

因爲你得到的文本區域中的文本具有:

document.getElementById("details").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>

相關問題