I have a text editor BBCode in Javascript (with a style in CSS ), but my problem is that the buttons to put in Bold, italic or underline do not work. If I put the codes both <b>
as </b>
or [b][/b]
manually, yes, I put what is inside the label in bold / italics / underline, but if I do not put it manual and I click on the button, does not do anything.
function mostrarTexto () {
var textArea = document.getElementById('miTexto');
var div = document.getElementById('mostrarTexto');
var text = textArea.value;
text = text.replace(/\</gi, "<");
text = text.replace(/\>/gi, ">");
text = text.replace(/\n/gi, "<br />");
text = text.replace(/\[b\]/gi, "<b>");
text = text.replace(/\[\/b\]/gi, "</b>");
text = text.replace(/\[i\]/gi, "<i>");
text = text.replace(/\[\/i\]/gi, "</i>");
text = text.replace(/\[u\]/gi, "<u>");
text = text.replace(/\[\/u\]/gi, "</u>");
div.innerHTML = text;
}
function seleccionModificacion (val1,val2) {
var textArea = document.getElementById('miTexto');
if( -1 != navigator.userAgent.indexOf ("MSIE") ) {
var rangoTexto = document.selection.createrangoTexto();
var rangoTextoGuardado = rangoTexto.duplicate();
if(rangoTextoGuardado.length > 0) {
rangoTextoGuardado.moveToElementText(textArea);
rangoTextoGuardado.setEndPoint('EndToEnd', rangoTexto);
textArea.selectionstart = rangoTextoGuardado.text.length - rangoTexto.text.length;
textArea.selectionend = textArea.selectionstart + rangoTexto.text.length;
}
}
if (typeof(textArea.selectionstart) != "undefined") {
var begin = textArea.value.substr(0, textArea.selectionstart);
var selection = textArea.value.substr(textArea.selectionstart, textArea.selectionend - textArea.selectionstart);
var end = textArea.value.substr(textArea.selectionend);
textArea.value = begin + val1 + selection + val2 + end;
}
}
.text_edit {
width: 500px;
height: 300px;
resize: none;
}
#view_text {
width: 500px;
}
<html>
<head>
<meta charset="utf-8" />
<title>Editor de texto</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<input type="button" value="B" onclick="seleccionModificacion('[b]','[/b]')" />
<input type="button" value="I" onclick="seleccionModificacion('[i]','[/i]')" />
<input type="button" value="U" onclick="seleccionModificacion('[u]','[/u]')" />
<br />
<textarea class="text_edit" id="miTexto" style="height:100px;width:400px"></textarea>
<br />
<input type="button" value="Mostrar texto" onclick="mostrarTexto()"/>
<div id="mostrarTexto"></div>
</body>
</html>