Insert HTML in Div with a substr - javascript

I am trying to insert an underline or blank space in a div that is being affected with a keyup function. The objective is to be able to move where the blank space is in the text. The keyup function works fine, the inserting of the blank space (div class underline) isnt.
HTML:
<div class="bigwhitecard" id="bigwhitecard"></div>
<textarea id="text" placeholder="Type your card here" name="text"></textarea>
Javascript/Jquery:
$(document).ready(function () {
$('#text').keyup(function(){
$('#bigwhitecard').html($(this).val());
});
var blankplace = 0;
$('#rightbtn').click(function() {
blankplace++;
});
$('#leftbtn').click(function() {
blankplace--;
});
var b = '<div class="underline"></div>';
$('#bigwhitecard').each(function() {
var blankplace = 0;
var txt = $(this).text();
if (txt.length>0) {
$(this).html(''+txt.substring(0,blankplace)+'<div class="underline"> </div>');
}
});
});

So use a substr to get the remaining text length that is left over and add it after the text.
var filler = "__________";
var out = document.getElementById("bigwhitecard");
document.getElementById("text").addEventListener("keyup", function() {
var txt = this.value,
placeholder = txt.length<filler.length ? '<span class="underline">' + filler.substr(0,filler.length-txt.length) + '</span>' : '';
out.innerHTML = txt + placeholder;
});
.underline {
text-decoration: underline
}
<div class="bigwhitecard" id="bigwhitecard"></div>
<textarea id="text" placeholder="Type your card here" name="text"></textarea>
And based on your comment
var out = document.getElementById("bigwhitecard");
document.getElementById("text").addEventListener("keyup", function() {
var txt = this.value,
ind = 6,
len = this.value.length,
pre = len > ind ? txt.substr(0,ind) : txt,
suf = len > ind ? txt.substr(ind) : "";
out.innerHTML = pre + "<span>_</sapn>" + suf;
});
.underline {
text-decoration: underline
}
<div class="bigwhitecard" id="bigwhitecard"></div>
<textarea id="text" placeholder="Type your card here" name="text"></textarea>

Related

Get Color Picker value in tags

I'm creating a text editor and so far everything is great, except for a little mess I don't know how to fix.
I need to get the value of the color selected by the user into the tag that is inserted into the textarea.
I don't reeally know how to use JSFiddle, but I think I can share it: https://jsfiddle.net/ElenaMcDowell/mh9rfwct/
<script>//Color picker
//color picker
var theInput = document.getElementById("colorChoice");
var theColor = theInput.value;
theInput.addEventListener("input", function() {
document.getElementById("hex").innerHTML = theInput.value;
}, false);
//Tags
function btnEditor(h, a, i) { // helloacm.com
var g = document.getElementById(h);
g.focus();
if (g.setSelectionRange) {
var c = g.scrollTop;
var e = g.selectionStart;
var f = g.selectionEnd;
g.value = g.value.substring(0, g.selectionStart) + a + g.value.substring(g.selectionStart, g.selectionEnd) + i + g.value.substring(g.selectionEnd, g.value.length);
g.selectionStart = e;
g.selectionEnd = f + a.length + i.length;
g.scrollTop = c;
} else {
if (document.selection && document.selection.createRange) {
g.focus();
var b = document.selection.createRange();
if (b.text != "") {
b.text = a + b.text + i;
} else {
b.text = a + "REPLACE" + i;
}
g.focus();
}
}// helloacm.com
}
</script>
And the HTML
<div class="fonts-box fonts-color" style="text-align: center;">
<form>
<input type="color" value="" id="colorChoice">
</form>
<p id="hex" style="padding-bottom: 3px;"></p>
<button id="colorSelect" onclick="btnEditor('ECEditor', '[color=#VALUEHERE]', '[/color]');">Select</button>
</div>
<textarea id="ECEditor" class="editor-textarea" name="editor-text"></textarea>
function btnEditor() {
var but = document.getElementById('wrapper')
var color = document.getElementById('colorChoice').value
console.log(color)
but.innerHTML = '<button id=\"colorSelect\" onclick=\"btnEditor(\'ECEditor\', \'[color=' + color + ']\',\'[/color]\');">Select</button>'
}
/*
this answer
<button id="colorSelect" onclick="btnEditor('ECEditor', '[color=#000000]','[/color]');">Select</button>
your request
<button id="colorSelect" onclick="btnEditor('ECEditor','[color=#VALUEHERE]','[/color]');">Select</button>
*/
<div class="fonts-box fonts-color" style="text-align: center;">
<form>
<input type="color" value="" id="colorChoice">
</form>
<p id="hex" style="padding-bottom: 3px;"></p>
<span id = 'wrapper'>
<button id="colorSelect" onclick="btnEditor();">Select</button></span>
</div>
const getCurrentColorPicker = () => {
return document.getElementById("colorChoice").value;
};
function btnEditor(h, a, i) {
console.log(getCurrentColorPicker());
// helloacm.com
var editor = document.getElementById(h);
editor.value = a + getCurrentColorPicker() + i;
// other code...
}

Simple formatting in textarea

I am trying to make a blog type of website. I got to a point where you can enter text into a textarea box and then click submit to have it appear below. However, I have come to a problem where it does not save the format of the input (notably for me, transforms paragraphs into spaces). I have read that this would require a rich-text editor, and I have tried TinyMCE but it gives a lot more options than needed or which would be able to be used in my case. Is there a simple way to fix this problem? If not, what is the best way to go about this?
I am mainly after the paragraph, tab, and multiple spaces formatting, everything else is currently not needed.
Here is what I currently have that is related:
HTML
<!-- Blog Section -->
<div class="itemBlog">
<h2 id="itemBlogTitle">My Blog</h2>
<textarea type="text" rows="10" cols="100" class="blogTextArea" id="blogInput"></textarea>
<div onclick="newBlog()" class="addBtn">Add</div>
<ul id="blogList"></ul>
</div>
<script src="itemblog.js"></script>
JavaScript
// Create a new blog item when clicking on the "Add" button
function newBlog() {
var li = document.createElement("li");
var inputValue = document.getElementById("blogInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue != '') {
document.getElementById("blogList").appendChild(li);
}
document.getElementById("blogInput").value = "";
var textarea = document.createElement("TEXTAREA");
var txt = document.createTextNode("\u00D7");
textarea.className = "close";
textarea.appendChild(txt);
li.appendChild(textarea);
for (i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = "none";
}
}
}
EDIT: white-space: pre-wrap; fixed it, thank you
If you want something simple, just save into your database the input content with id description, after that it will respect the paragraph and spaces.
JQUERY
$('#test').keyup(function() {
var text = $(this).val();
var description = text.replace(/ /g, ' ').replace(/[\n]/g, '<br>');
$('#text').html(description)
$('#description').val(description)
});
<textarea id="test" cols="30" rows="10"></textarea>
<input id="description" name="description" hidden>
<div id="text"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
js
function formatString(el) {
var str = el.value;
str = str.replace(/ /g, ' ').replace(/[\n]/g, '<br>');
document.getElementById('text').innerHTML = str;
document.getElementById('description').value = str;
}
<textarea onkeyup="formatString(this)" cols="30" rows="10"></textarea>
<input id="description" name="description" hidden>
<div id="text"></div>
You can create a function nl2br() as folows:
function nl2br (str, is_xhtml) {
if (typeof str === 'undefined' || str === null) {
return '';
}
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
You can see more here

How to integrate counting frequency of characters in a string using javascript

I have some simple HTML code
<textarea id="text" placeholder="Type text...."></textarea>
<a id="button" class="button"></a>
<textarea id="result" disabled></textarea>
and I have a javascript code
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
I just want to integrate js with HTML to count each character frequency inside of textarea with id="text" and show result inside of textarea with id="result". I have tried to use
document.getElementById("text").value;
but something goes wrong and still not working. There is any way to do this in easy way?
If you want to do it while typing you can use the keyup event on the textarea, in the following way
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
window.addEventListener('load', function() {
const textbox = document.getElementById('text');
const result = document.getElementById('result');
textbox.addEventListener('keyup', function() {
const frequency = getFrequency( textbox.value );
result.value = Object.keys( frequency ).map( key => `${key}: ${frequency[key]}` ).join('\n');
});
});
<textarea id="text" placeholder="Type text...."></textarea>
<a id="button" class="button"></a>
<textarea id="result" disabled></textarea>
if you want to do it upon button click, you could change the previous code like so:
document.getElementById('button').addEventListener('click', function() {
const frequency = getFrequency( textbox.value );
result.value = Object.keys( frequency ).map( key => `${key}: ${frequency[key]}` ).join('\n');
});
This should do it.
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
document.getElementById('myButton').onclick = function(){
var str = document.getElementById('text').value;
var result = getFrequency(str);
document.getElementById('result').value = JSON.stringify(result);
}
<textarea id="text" placeholder="Type text...." ></textarea>
<button id="myButton" class="button">Count</button>
<textarea id="result" disabled></textarea>
Using spread syntax, Map, Array#reduce, and String#split
const textArea = document.getElementById("text");
const button = document.getElementById("button");
const result = document.getElementById("result");
button.addEventListener("click", function(){
const value = textArea.value.trim();
const res = getFrequency(value);
console.log(JSON.stringify([...res]));
result.innerText = `(${[...res].join("), (")})`;
})
function getFrequency(str){
return str.split("").reduce((a,c)=>a.set(c, (a.get(c) || 0) + 1), new Map());
}
div {
display: flex;
background-color: lightgrey;
flex-direction: column;
}
div > div {
flex-direction: row;
}
<div>
<textarea id="text" placeholder="Type text....">
Some text to check the count of characters
</textarea>
<div>
<button id="button" class="button">Click me</button>
<p id="result"></p>
</div>
</div>

Remove line with specific word from text area using javascript

I am trying to remove line with specific word using javascript from textarea.
Here is example
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
If the user enters the value in input field the line which contains it should be removed. Suppose user enters CxPh1tgiK2g or xOYPv7CxMVk the line which contains those ids should be removed
Try
$("#remove").click(function() {
var text = $("#id").val()
var lines = $('#textarea').val().split('\n');
lines = lines.filter(function(val) {
if (val.match(text)) return false
else return true
})
$('#textarea').text(lines.join('\n'))
})
$("#replace").click(function() {
var text = $("#id").val()
var lines = $('#textarea').val().split('\n');
var n = Math.floor(Math.random()*lines.length)
lines[n] = lines[n].replace(/\?v=([A-Za-z0-9]){11}/, "?v="+text)
$('#textarea').text(lines.join('\n'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="id" />
<input type="button" id="remove" value="Remove" />
<input type="button" id="replace" value="Replace" />
<br/>
<textarea id="textarea" rows="4" cols="150">
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
</textarea>
As solution to remove line with inclusion
var value = test.value.split(/\n/g).filter(function(val)
{
return val !== "";
});
console.log(value);
setTimeout(function()
{
var index = value.findIndex(function(val)
{
return val.includes('kKC7-ACrs1w');
});
if (index !== -1)
{
value.splice(index, 1);
test.value = value.join("\n");
}
}, 2000);
.text {
width: 100%;
resize: none;
height: 200px;
}
Line with <b>kKC7-ACrs1w </b>will be removed in 2 secs
<textarea name="" id="test" class=text >
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
</textarea>
You can do something like this:
var ta = document.querySelector("textarea");
var lines = ta.innerHTML.split("\n");
var id = "omg";
for (var i = 0; i < lines.length; i ++) {
if (lines[i].indexOf(id) > -1) {
lines.splice(i, 1);
}
}
ta.innerHTML = lines.join("\n");
<textarea>
lol
omg
js
</textarea>

strip html from textarea on button click and store the stripped text

I try to load the value of a textarea into a variable on button
click,
then stripe all html tags except of the html tags br and strong
then save the new value into another variable.
I found this solution which works on a normal div, but does not seem to work with textareas. So I created a temporary div and set it's html to the value of the textarea.
//Create a temporary div and initialize it with the value from the first param
var tmp = document.createElement("DIV");
tmp.id = "tmp";
tmp.innerHTML = html;
This is my attempt which is not working. I think because i create the div dynamically and jQuery is not aware of it's existence?
//init the textarea value for this example
$("textarea#message").val
(
"<div>\n"+
"<strong>Hello Universe</strong>\n"+
"<br><p>Spread good Vibes :)</p>\n"+
"</div>"
);
$("div#mybutton").on
(
"click",
function()
{
var textarea = document.getElementById("message");
var allText = textarea.value;
var newText = strip_tags(allText, "strong, br");
//now do something with the new text
textarea.value = newText;
console.log(newText);
}
);
function strip_tags(html, exceptions)
{
console.log(html);
//Create a temporary div and initialize it with the value from the first param
var tmp = document.createElement("DIV");
tmp.id = "tmp";
tmp.innerHTML = html;
document.body.appendChild(tmp);
//Strip tags and return the whole stripped text
$("#tmp *").not(exceptions).each(function(){
var content = $(this).contents();
$(this).replaceWith(content);
});
}
div#mybutton {
border: 1px solid black;
width: 80px;
text-align: center;
}
div#mybutton:hover {
cursor: pointer;
color: white;
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<textarea id='message' autofocus maxlength="500" rows="4" cols="50"></textarea>
<div id="mybutton"> PRESS </div>
</div>
One complete jQuery plugin would be:
jQuery.fn.extend({
stripHtmlTags: function() {
function getDivContent(input) {
return $('<div></div>').html(input.val());
};
function addCheckboxes(input) {
var div = getDivContent( input );
input.siblings('.tags-checkboxes').remove();
var tagsCheckboxes = $('<div class="tags-checkboxes"></div>');
var fake = getDivContent(input);
var allTags = [];
fake.find('*').each(function(i) {
var thisTag = $(this).prop("tagName").toLowerCase();
if( $.inArray(thisTag, allTags)==-1 ) {
allTags.push( thisTag );
};
});
$.each(allTags, function(t, tag) {
var uniqueId = tag + '-' + Math.round(new Date().getTime() + (Math.random() * 100));
tagsCheckboxes.append('<span class="strip-tags-option"><input type="checkbox" id="' + uniqueId + '" value="' + tag + '" checked="checked" /> <label for="' + uniqueId + '">' + tag + '</label></span>');
});
input.after( tagsCheckboxes );
return tagsCheckboxes;
};
function addStripButton(input) {
var button = $('<button class="strip-tag-button">STRIP TAGS</button>');
input.next().after( button );
return button;
}
function strip(input, checkboxes) {
var fake = getDivContent(input);
var tagsArray = [];
checkboxes.find('input').each(function(i) {
var thisCheckbox = $(this);
if( thisCheckbox.is(':checked') ) {
tagsArray.push( thisCheckbox.val() );
};
});
var tags = tagsArray.join(', ');
console.log( tags );
fake.find(tags).contents().unwrap();
fake.find(tags).remove();
input.val(fake.html());
addCheckboxes(input);
};
return this.each(function() {
var thisInput = $(this);
if( !thisInput.hasClass('initialized') ) {
var checkboxes = addCheckboxes( thisInput );
var stripButton = addStripButton( thisInput );
stripButton.on('click', function(e) {
e.preventDefault();
strip(thisInput, checkboxes);
});
thisInput.on('input', function(e) {
checkboxes.remove();
checkboxes = addCheckboxes( thisInput );
});
thisInput.addClass('initialized');
};
});
}
});
var message = $('#message');
message.val("\
<div>\n\
<strong>Hello Universe</strong>\n\
<a href='#' title='Test'>Test link</a>\n\
<br><p>Spread good Vibes :)</p>\n\
</div>\
");
message.stripHtmlTags();
.strip-tags-option {
display: inline-block;
margin-right: 10px;
}
.strip-tag-button {
border: 1px solid black;
text-align: center;
}
.strip-tag-button:hover {
cursor: pointer;
color: white;
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<textarea id='message' autofocus maxlength="500" rows="4" cols="50"></textarea>
</p>
Also on JSFiddle.
Credits to this answer.
I found the solution, there were two problems.
1. I had to append the created DIV to the DOM.
2. I returned already before the first cycle.
Now it works, and basically I just developed the equivallent from the PHP function strip_tags ;) Credits to karim79 for his contribution.
//init the textarea value for this example
$("textarea#message").val
(
"<div>\n"+
"<strong>Hello Universe</strong>\n"+
"<br><p>Spread good Vibes :)</p>\n"+
"</div>"
);
$("div#mybutton").on
(
"click",
function()
{
var textarea = document.getElementById("message");
var allText = textarea.value;
var newText = strip_tags(allText, "br");
//now do something with the new text
textarea.value = newText;
}
);
//strips all html tags from a string except the tags from the whitelist, and returns the new string. (this function works exactly as the PHP equivalent strip_tags http://php.net/manual/de/function.strip-tags.php)
function strip_tags(str, whitelist)
{
console.log("TEXT BEFORE STRIPE: (whitelist: "+whitelist+")\n\n"+ str);
//Create a temporary div and initialize it with the value from the first param
var tmp = document.createElement("DIV");
tmp.id = "tmp";
tmp.innerHTML = str;
document.body.appendChild(tmp);
//Strip tags and return the whole stripped text
$("#tmp *").not(whitelist).each(function(){
if ($(this).is("br"))
{
$(this).remove();
}
var content = $(this).contents();
$(this).replaceWith(content);
});
var newText = tmp.innerHTML;
tmp.remove();
console.log("----------------------------------------------------------");
console.log("TEXT AFTER STRIPE: (whitelist: "+whitelist+")\n"+ newText);
return newText;
}
div#mybutton {
border: 1px solid black;
width: 80px;
text-align: center;
}
div#mybutton:hover {
cursor: pointer;
color: white;
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<textarea id='message' autofocus maxlength="500" rows="4" cols="50"></textarea>
<div id="mybutton"> PRESS </div>
</div>
You can use regex for that
$(function() {
var html = $('textarea').val();
console.log(html.replace(/<(?!strong|br\/?)[^>]+>/g, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea><strong>foo</strong><br/><div>hello</div></textarea>
and if you want to have tags in variable you can use this code:
$(function() {
var tags = ['strong', 'br\\/?'];
var regex = new RegExp('<(?!'+tags.join('|')+')[^>]+>', 'g');
var html = $('textarea').val();
console.log(html.replace(regex, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea><strong>foo</strong><br/><div>hello</div></textarea>

Categories