2009-04-11 8 views

Répondre

24

Cela fonctionne:

function replaceIt(txtarea, newtxt) { 
 
    $(txtarea).val(
 
     $(txtarea).val().substring(0, txtarea.selectionStart)+ 
 
     newtxt+ 
 
     $(txtarea).val().substring(txtarea.selectionEnd) 
 
    ); 
 
} 
 
    
 

 
$("button").on('click', function() { 
 
    replaceIt($('textarea')[0], 'fun') 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<textarea>Hello world.</textarea> 
 
<button>Replace with fun</button>

2

J'ai trouvé ceci:

function wrapText(elementID, openTag, closeTag) { 
 
    var textArea = $('#' + elementID); 
 
    var len = textArea.val().length; 
 
    var start = textArea[0].selectionStart; 
 
    var end = textArea[0].selectionEnd; 
 
    var selectedText = textArea.val().substring(start, end); 
 
    var replacement = openTag + selectedText + closeTag; 
 
    textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len)); 
 
} 
 

 
$('button').on('click', function() { 
 
    wrapText('test', '<b>', '</b>'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<textarea id="test">This is a test</textarea> 
 
<button>Surround with &lt;b&gt; tag</button>

Mais personellement sa ne fonctionne pas avec le contenu-Edita ble divs.

Questions connexes