I currently have this code: https://jsbin.com/hocisirovo/edit?html,css,js,output
With the button, it bolds the entire text in the text box. How can I bold only what I select in the text box? The easy way would be to use execCommand but I cannot use that.
Any help is appreciated.
Thanks!
I didn't quite get your question but you could use an editable div to make parts of your text bold.
<html>
<head>
<script>
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
}
return text;
}
function boldSelected(){
var textBox = document.getElementById("textbox");
var text = textBox.innerHTML;
var boldText = getSelectionText();
var offset1 = text.indexOf(boldText);
var offset2 = offset1 + boldText.length;
var str1 = text.substring(0,offset1);
var str2 = text.substring(offset2,text.length);
textBox.innerHTML=str1+"<b>"+boldText+"</b>"+str2;
}
function undoBold(){
if(document.getElementById("textbox").innerHTML == "<b></b>")
document.getElementById("textbox").innerHTML == "";
}
</script>
</head>
<body>
<div onkeypress="undoBold()" contentEditable="true" id="textbox" style="width:30%; border:1px solid #0a0a0a;padding:3px;"></div></br>
<button onclick="boldSelected()">Bold</button>
</body>
</html>
Related
I'm trying to prepare a Javascript function that changes the "selected text" url to fully active HTML Hyperlinks.
My HTML code is:
<html>
<body>
<textarea id="my_input" cols="32" rows="16" textToDisplay>Some text with https://www.google.pl/?gws_rd=ssl for simple WYSIWYG function</textarea>
<input type="submit" value="[to url]" onclick="make_url('my_input')" />
</body>
</html>
My js function:
<script>
function make_url(my_input) {
var my_input=document.getElementById(my_input);
var selected_text=window.getSelection();
my_input.value=my_input_begin.value + ''+ selected_text +'' + my_input_end.value;
}
</script>
But after selecting https://www.google.pl/?gws_rd=ssl and pressing submit I get empty HTML Hyperlinks. What is wrong? window.getSelection() / document.getSelection() doesn't get the selected text.
The second question is - how to get my_input_begin.value and my_input_end.value or replace only "selected" part of my <textarea> entry?
I've sorted it out. The final Javascript code is:
function text_to_hyperlink(input_id) {
var text_entry = document.getElementById(input_id);
var text_selected;
// for IE
if (document.selection != undefined) {
text_entry.focus();
var sel = document.selection.createRange();
text_selected = sel.text;
}
// others browsers
else if (text_entry.selectionStart != undefined) {
var selection_pos_start = text_entry.selectionStart;
var selection_pos_end = text_entry.selectionEnd;
text_selected = text_entry.value.substring(selection_pos_start, selection_pos_end);
selection_prefix = text_entry.value.substring(0, selection_pos_start);
selection_sufix = text_entry.value.substring(selection_pos_end, text_entry.length );
}
text_entry.value = selection_prefix + '' + text_selected + '' + selection_sufix;
}
I replace all entry text_entry with HTML hyperlink code. But I didn't find how to easy replace the text_selected with text_selected
Final HTML:
<textarea id="my_input" cols="32" rows="16" textToDisplay>Some text with https://www.google.pl/?gws_rd=ssl for simple WYSIWYG function</textarea>
<input type="submit" value="[url]" onclick="text_to_hyperlink('my_input')"/>
Try this code:
<html>
<head>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
</head>
<body>
<textarea id="my_input" cols="32" rows="16" onclick="this.focus();this.select()">Some text with https://www.google.pl/?gws_rd=ssl for simple WYSIWYG function</textarea>
<p id="link"></p>
<input type="button" value="[to url]" onclick="make_url()" />
</body>
Click on the textArea first to get the text selected and then click on [to url] button.
<script>
function make_url() {
var textComponent = document.getElementById("my_input");
var selectedText;
// IE version
if (document.selection != undefined)
{
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
// Mozilla version
else if (textComponent.selectionStart != undefined)
{
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos)
}
var link = document.getElementById("link");
var a = document.createElement("a");
var href = document.createTextNode("Link");
a.appendChild(href);
a.setAttribute("href", selectedText);
document.body.appendChild(a);
}
Note: Every time you add new text in the textArea and click on the [to url] button a new hyper link will be generated.Also i have used jquery library to select the so you have to attach it on the page.
Hope it works fine ☻
I have a contenteditable div that serves as an editor to allow users to input and save text. Upon clicking a save button, I prompt them to ask what they want to save the text as.
The title is then saved to localstorage and appended to a separate div, where they click the title and the text they saved it under will appear in the editor.
The issue now is that whenever I refresh the page, the appended data disappears. Was wondering how I could keep the appended data there on refresh? Also, I need it to still be able to link to its content, not just become a bunch of text in a div.
I've simplified the entire code here:
<!doctype html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js">
</script>
</head>
<body>
<div style="width:10em; height:10em; border-style:solid; border-color:black;" id="editor1" contenteditable="true"></div>
<button id="savebtn">Save Changes</button>
<div style="width:10em; height:5em; border-style:solid; border-color:red;" id="Contentable"></div>
<script>
var editElem = document.getElementById("editor1");
$(document).ready(function() {
$("#savebtn").click(function() {
var title = prompt("What would you like your title to be?");
localStorage.setItem(title, editElem.innerHTML);
titles = localStorage.getItem("titles");
if (titles == null) {
titles = [];
} else {
titles = JSON.parse(titles);
}
titles.push(title);
localStorage.setItem("titles", JSON.stringify(titles));
var htmlData = "<a onclick=showData('" + title + "')>" + title + "</a><br>";
$("#Contentable").append(htmlData);
var userVersion = editElem.innerHTML;
localStorage.setItem("userEdits", userVersion);
editElem.innerHTML = "";
});
});
function showData(txt) {
editElem.innerHTML = localStorage.getItem(txt);
}
</script>
</body>
</html>
EDIT: How can I also remove the data from the div using say a "remove" button? In the event where the div gets too packed and there are some useless titles that the user wants the remove.
Try this ... i hope it works
<!doctype html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js">
</script>
<style type="text/css">
.selected{
background-color: blue;
color:white;
}
</style>
</head>
<body>
<div style="width:10em; height:10em; border-style:solid; border-color:black;" id="editor1" contenteditable="true"></div>
<button id="savebtn">Save Changes</button>
<button id="remove">Remove Data</button>
<div style="width:10em; height:5em; border-style:solid; border-color:red;" id="Contentable"></div>
<script>
var editElem = document.getElementById("editor1");
$(document).ready(function() {
$("#savebtn").click(function() {
var title = prompt("What would you like your title to be?");
localStorage.setItem(title, editElem.innerHTML);
titles = localStorage.getItem("titles");
if (titles == null) {
titles = [];
} else {
titles = JSON.parse(titles);
}
titles.push(title);
localStorage.setItem("titles", JSON.stringify(titles));
var htmlData = "<a onclick=showData('" + title + "')>" + title + "</a><br>";
$("#Contentable").append(htmlData);
var userVersion = editElem.innerHTML;
localStorage.setItem("userEdits", userVersion);
editElem.innerHTML = "";
});
});
function showData(txt) {
editElem.innerHTML = localStorage.getItem(txt);
}
function loadData()
{
var htmlData=localStorage.getItem("titles");
htmlData=htmlData.replace(/\[|\]/g, "");
htmlData=htmlData.replace(/["']/g, "")
htmlData=htmlData.split(",");
var arlength=htmlData.length;
console.log(arlength)
for(num=0;num<arlength;num++)
{
$("#Contentable").append("<a onclick=showData('" + htmlData[num] + "')>" + htmlData[num] + "</a><br>");
}
}
loadData();
var selected;
$("#Contentable a").click(function(){
selected=$("#Contentable a").index(this);
$("#Contentable a").removeClass("selected")
$(this).addClass("selected");
})
$("#remove").click(function(){
$("#Contentable a:eq("+selected+")").remove();
// Some Delete codes to localStorage here=================================
})
</script>
</body>
</html>
I want to remove rich text from my contenteditable div keep only newline or br tags when paste something from clipboard.
I'm trying but its doesn't work
http://jsfiddle.net/marco83/zkf5jkqu/
<div id="editableDiv" contentEditable="true" style="min-height: 200px; border: solid 1px #0099FF;"></div>
<input type="button" value="remove" onclick="strip();">
<script>
function strip() {
var mydiv = document.getElementById("editableDiv");
var str = mydiv.innerHTML;
str = str.replace(/<br>/gi, "\n");
str = str.replace(/<(?:.|\s)*?>/g, "");
mydiv.innerHTML = str;
}
</script>
I copy the text from this page http://www.jacklmoore.com/autosize/
I know it doesn't have any <br> tag the text. but how can i do like Twitter does like this? Thanks.
Try This
<script>
function strip() {
var mydiv = document.getElementById("editableDiv");
var str = mydiv.innerHTML;
mydiv.innerHTML = remove_tags(str);
}
function remove_tags(html) {
html = html.replace(/<br>/g, "$br$");
html = html.replace(/(?:\r\n|\r|\n)/g, '$br$');
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
html = tmp.textContent || tmp.innerText;
html = html.replace(/\$br\$/g, "<br>");
return html;
}
</script>
Example Here
So what i am doing is, i am replace <br> and \n with a placeholder $br$ so as to preserve them and then i am removing all the HTML tags from the string and replacing $br$ back with <br>
Problem : So I have alerted the value of textarea by:
var source = document.getElementById('source').value;
alert(source);
But the value of textarea is alerted as it was at the time of page load. And I want to alert current value of the textarea. I have also tried
$("form").submit(function(){
But that also haven't helped me. So how can I do this?
This is my code.
<html>
<head>
<title>Perl WEB</title>
<script type="text/javascript" src="http://code.guru99.com/Perl1/codemirror.js"></script>
<link rel="stylesheet" href="http://code.guru99.com/Perl1/codemirror.css" type="text/css" media="screen" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://code.guru99.com/perl/perl.js"></script>
<style>
.CodeMirror {
border: 1px solid #eee;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
<script>
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
});
});
</script>
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg.CORE.warn = function(List__) {
var i;
List__.push("\n");
for (i = 0; i < List__.length; i++) {
document.getElementById('log-result').value += p5str(List__[i]);
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = document.getElementById('source').value;
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('log-result').value = "";
// document.getElementById('js-result').value = "";
document.getElementById('print-result').value = "";
try {
// compile
document.getElementById('log-result').value += "Compiling.\n";
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
document.getElementById('log-result').value += "Compilation time: " + time + "ms\n";
// document.getElementById('js-result').value += js_source + ";\n";
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
document.getElementById('log-result').value += "Running time: " + time + "ms\n";
p5pkg.CORE.print(["\nDone.\n"]);
}
catch(err) {
document.getElementById('log-result').value += "Error:\n";
document.getElementById('log-result').value += err + "\n";
document.getElementById('log-result').value += "Compilation aborted.\n";
}
}
</script>
</head>
<body>
<form>
<textarea id="source" cols="70" rows="10">
say 'h';
</textarea>
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="button" value="Run" onclick="execute()"/></br>
Output:</br>
<textarea id="print-result" disabled="true" rows="10" cols="70"></textarea></br>
Log:</br>
<textarea id="log-result" disabled="true" cols="70"></textarea>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("source"), {
lineNumbers: true,
indentUnit: 4,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
</script>
</form>
</body>
</html>
So how can I get the current value of the textarea? Please help me guys.
I'm not familiar with CodeMirror, but what you exactly see on the screen, is not your original #source anymore. Instead there are several elements created by CodeMirror, and the original textarea is hidden.
When I look at the documentation, I found this:
var source = editor.doc.getValue();
alert(source);
Or, since you've constructed the editor object with fromTextArea() method, you can update the value of the the textarea before reading it:
editor.save();
var source = document.getElementById('source').value;
alert(source);
Notice also what Adam has said about submitting the form. And there are invalid </br> tags in your HTML, the correct form is <br />.
Please visit at CodeMirror User Manual for the furher information.
As you have jQuery loaded you can do as follows:
var content = $('#source').val();
alert(content);
Of course, if you do it at page load, the textarea will be empty (or even uncreated). You could extract its content on form submit, as you seem to suggest.
This code will create a button that will alert the content of your textarea when clicked:
<button onclick="alert($('#source').val())">Click me</button>
Try the following inside the submit()
var textAreaVal = $("#print-result").val();
alert(textAreaVal);
Your form does not get submitted when the button in it is pressed since this is not a submit button.
This will not submit the form, and will not alert its' contents.
<input type="button" value="Run" onclick="execute()"/></br>
Add something like this in the form:
<input type="submit" value="Submit">
if yout want the value to alert when the mouse leaves the textarea you could try to add onblur="myFunction()" to the input something like: (actually if you want it on mouse leave, you can add onmouseout="myFunction()")
<textarea id="source" cols="70" rows="10" onblur="myFunction()">
say 'h';
</textarea>
<script type="text/javascript">
function myFunction() {
var source = document.getElementById('source').value;
alert(source);
}
</script>
I need a very simple Javascript on a html page, that will do the following..
Display a text like:
This is a string of text and can be long
then if you mark some of the text with your mouse, the selected text should be inserted and automatically updated into a text field
How can i do it?
Create readonly textarea (you may use CSS to decorate it as simple text block). Then process it's onSelect event to precess selection. You will get something like:
<script language="JavaScript">
function display(txtarea)
{
var sl = (txtarea.value).substring(txtarea.selectionStart, txtarea.selectionEnd);
alert (sl);
}
</script>
<textarea name="entry" onSelect="display(this);">Some text.</textarea>
<script type="text/javascript">
function render(element)
{
var stext = element.value.substring(element.selectionStart, element.selectionEnd);
document.getElementById('selText').value = stext;
}
</script>
<input id="selText" value="" />
<textarea name="entry" onclick="render(this);">This is a string of text and can be long
</textarea>
Hope this helps
Solution with jQuery Based on this link
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var textSelected = function(el, elResult) {
var len = el.val().length;
var textarea = document.getElementById(el.attr("id"));
if($.browser.msie) {
if (document.selection) {
var range = document.selection.createRange();
var stored_range = range.duplicate();
stored_range.moveToElementText(textarea);
stored_range.setEndPoint('EndToEnd', range);
textarea.selectionStart = stored_range.text.length - range.text.length;
textarea.selectionEnd = textarea.selectionStart + range.text.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
}
} else {
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
}
var sel = textarea.value.substring(start, end);
if (sel.length!=0)
elResult.val(sel);
};
$("#text-entry").bind("select", function(){
textSelected($(this), $("#select-text"));
});
});
</script>
</head>
<body>
<input id="select-text" type="text" /><br />
<textarea id="text-entry">text for select</textarea>
</body>
</html>