lofaifa Posted March 20, 2012 Share Posted March 20, 2012 like forums text editors , i have a piece of text and i wanna make it bold , first i select the text and click a button //this is an example how can i do that in javascript ? , how can the javascript function know the selected text ? Link to comment https://forums.phpfreaks.com/topic/259354-how-to-surround-a-text-by-tag-using-a-button/ Share on other sites More sharing options...
smerny Posted March 20, 2012 Share Posted March 20, 2012 try something like this var sel = window.getSelection().getRangeAt(0); var content = "[b]"+sel.extractContents()+"[/b]"; sel.text(content); Link to comment https://forums.phpfreaks.com/topic/259354-how-to-surround-a-text-by-tag-using-a-button/#findComment-1329540 Share on other sites More sharing options...
lofaifa Posted March 20, 2012 Author Share Posted March 20, 2012 thank you . Link to comment https://forums.phpfreaks.com/topic/259354-how-to-surround-a-text-by-tag-using-a-button/#findComment-1329542 Share on other sites More sharing options...
smerny Posted March 20, 2012 Share Posted March 20, 2012 did that work, unmodified? i am unable to test now so i'm curious doubting it worked.. Link to comment https://forums.phpfreaks.com/topic/259354-how-to-surround-a-text-by-tag-using-a-button/#findComment-1329543 Share on other sites More sharing options...
lofaifa Posted March 20, 2012 Author Share Posted March 20, 2012 thank you != worked i found a function : function applyTag(obj,tag) {wrapText(obj, '['+tag+']', '[/'+tag+']');}; function wrapText(obj, beginTag, endTag) { if(typeof obj.selectionStart == 'number') { // Mozilla, Opera, and other browsers var start = obj.selectionStart; var end = obj.selectionEnd; obj.value = obj.value.substring(0, start) + beginTag + obj.value.substring(start, end) + endTag + obj.value.substring(end, obj.value.length); } else if(document.selection) { // Internet Explorer // make sure it's the textarea's selection obj.focus(); var range = document.selection.createRange(); if(range.parentElement() != obj) return false; if(typeof range.text == 'string') document.selection.createRange().text = beginTag + range.text + endTag; } else obj.value += text; }; and this in You page : <input type="button" value="bold" onclick="applyTag(document.getElementById('question_text'),'strong')" /> Link to comment https://forums.phpfreaks.com/topic/259354-how-to-surround-a-text-by-tag-using-a-button/#findComment-1329553 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.