underline a part of text in Textarea [duplicate] - javascript

This question already has answers here:
Rendering HTML inside textarea
(7 answers)
Underlining text of a textarea
(4 answers)
Closed 8 years ago.
is it possible to underline a portion of text in control.
I did like this in jquery, but no underline is appearing. any sample code examples?
<textarea rows = "3" cols = "50" id = "TestName" ></textarea>
Jquery
var dvHTML = ''
dvHTML = '<span style=text-decoration: underline;>' + "Hello world" + '</span>';
$("#TestName").html(dvHTML);
Output i'm getting as only Hello world, tags are not getting recognized

You can use a contenteditable div.
<div contenteditable="true">I am saying <span>Hello</span></div>
Working Fiddle

You can't do that on textarea, You'll need some WYSIWYG if you need style on it.
Or you can fake user by adding div above of the textarea, and hide the textarea it self.

If you just want to underline the specific text you can use:
<textarea style="text-decoration:underline;" rows="20" cols="30" id="text">All are Welcome!!</textarea>
$("document").ready(function() {
$("#text").val($("#text").text());
$('textarea').keypress(function(e) {
$(this).css('text-decoration','none');
});
});
Demo: http://jsfiddle.net/fiddleyetu/czZWp/6/

Add double inverted commas " in style tag first and then a semicolon after divHtml = ''
This will work -
<!DOCTYPE html>
<html>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<textarea rows = "3" cols = "50" id = "TestName" style="text-decoration: underline;"></textarea>
<script>
var dvHTML = '';
dvHTML = "Hello world" ;
$("#TestName").html(dvHTML);
</script>
</body>
</html>
And to let you know the difference, the HTML that you enter inside the textarea will be its text. It will render it as text. So instead add text decoration as style of text area. And, about your original question - its not possible with textarea. See this -
Rendering HTML inside textarea

You can't do with a text area, the solution is to use an editable div.
HTML:
<div id="foo">
</div>
JS:
var dvHTML = '<span style="text-decoration: underline;">Hello world</span>';
$("#foo").html(dvHTML).click(function() {
this.contentEditable = true;
});
THE LIVE DEMO.

Related

txt.replace </blockquote> in textarea js

I give up! I looked at many different answers. I've tried many different ways and nothing works. I want to change the </blackquote> tag to <br /> or a new line in the textarea. Alternatively, change to some other character, because later I can replace another character in PHP to <br/>. How to do it?
Working example for easy understand here: https://jsfiddle.net/jsf88/rb3xp7am/35/
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎 </blockquote><br />
"X" -- HERE I want BR_TAG or new line in textarea after click 'quote' 😐
</div>
</section>
$(document).on('ready', function() {
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').text();
//txt = txt.replace('</blockquote>', '<br/>');
//txt = txt.replace(/<\/(blockquote)\>/g, "<br/>");
//txt = txt.replace(/blockquote*/g, '<br/>');
//txt = txt.replace(/(.*?)<\/blockquote>(.*?)/g, ' xxx ');
txt = txt.replace(/<\/blockquote>/gi, '<br/>')//NOT WORKING!!
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');//working great
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]'));
});
});
To make it funnier, another example with changing the blackquote tag to br works without a problem. Why? can someone explain it?
//OTHER EXAMPLES WHERE CHANGE </BLACKQUOTE> to <br/> WORKING GOOD... WTF?!
string = ` <blockquote>this is a quote for comment😎 </blockquote><br />"X" -- HERE I want BR_TAG or new line in textarea after click 'quote' 😐`;
string = string
.replace(/<\/blockquote>/gi, ' <br /> ');//but here working! ;/
console.log(string);
you recover text with text function ('.replyMsg').text() but in that case you will have the text but with no html tag like <blockquote> so first you will have to recover the html to have the blockquote tag
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
the br tag is not interpreted in textarea so you have to change it by a new line character
don't forget to remove opened bloquote tag to get the expected result
txt = txt.replace(/<blockquote>/gi, '');
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');
txt = txt.replace(/<\/blockquote>/gi, '\n');
txt = txt.replace(/<blockquote>/gi, '');
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]'));
});
blockquote {
background-color: silver;
}
.replyMsg {
border: 2px solid green;
}
.quoteMsg {
background-color: green;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎 </blockquote>
"X" -- HERE I want BR_TAG or new line in textare a after c lick 'quote' 😐
</div>
</section>
The first problem in your code was how you were adding the event listener to the ready event. Being it something invented by jQuery, and not a native event, the correct way to do it should be as of now (v.3.3.1 the version I used in this demo) $(document).ready(()=>{/*code here*/}).
As a further reference:
https://api.jquery.com/ready/
There is also $(document).on( "ready", handler ), deprecated as of
jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes
ready before this event is attached, the handler will not be executed.
But... it's not perfectly clear how did you wish to transform your text before setting the value of the textarea. So I just better factored your logic so that you have some clear steps:
grabbing the blockquote element text content and trimming it (being the origin)
applying the transform newline to whitespace (with the regex that I left untouched)
build the final string as a template literal that will include the quote content, the meta tags wrapping it, AND anything else you wish to add like for example a new line (\n) that in this example is exacerbated by a text following it.
There's a hint in your words that put me in the position to say something superflous but still deserving an attempt: the value of a inner text is just plain text and doesn't render html content. So the <br> itself would remain as you read it and wouldn't have any rendering effect on the textarea content. That's why I focused my demonstration on putting a newline with the escaping sequence. It works both on double quoted strings and template literals: "\n" `\n`
Further notes
It seems the original approach of processing the blockquote html was preferred. It's worth saying that it was appearently a terrible strategy for several reasons:
It grabs the blockquote content as html despite that's not how it's
rendered on the page.
It takes the effort to consider the whole outerHTML removing the
wrapping blockquote tags instead of fetching directly the innerHTML.
It adds the newline as newline instead of embedding it as <br> so
at this point I ask myself if the content in the textarea was
supposed to be encoded html or not.. and the added br would then
belong to something meta?
It's harder to deal with in case you want to further customize the
string processing
But... maybe there's something I didn't get and I'm doing weak assumptions.
//since you are using the ready event with jquery, that's the correct syntax
$(document).ready(function() {
$('.quoteMsg').click(function() {
//grabs the text content of the blockquote element (trimming it)
var quoteTextContent = $(this).closest('.replyBox').find('.replyMsg').text().trim();
//performs the transform already in place in your code.. replacing newlines with white spaces
quoteTextContent = quoteTextContent.replace(/(?:\r\n|\r|\n)/g, ' '); //working great
//builds the string to set the textarea value with, using a template literal
//here you can add anything you want.. like a new line but that's just an example
const encoded = `[quote]${quoteTextContent}[/quote]\nand something following to show the new line happening`;
console.log(encoded);
$("textarea[name='quote']").val( encoded );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎
<br>
Having new lines also ... since you perform a regex transform newline=>whitespace
</blockquote><br />
</div>
</section>
Well, thanks for answers. The problem was a missing .html tag.
This script work for me almost perfect for quoting few times:
$(document).on('ready', function() {
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');
txt = txt.replace(/</g, "<");
txt = txt.replace(/>/g, ">");
txt = txt.replace(/&/g, "&");
txt = txt.replace(/"/g, '"');
txt = txt.replace(/'/g, "'");
txt = txt.replace(/<br>/g, "");
txt = txt.replace(/<hr>/g, "[hr]");
//txt = txt.replace(/<hr>/g, "\n");
txt = txt.replace(/<blockquote>/gi, '');
txt = txt.replace(/<\/blockquote>/gi, '[hr]');
txt = txt.replace(/[hr][hr]/gi, "");//not working ([][])
txt = txt.replace(/[hr][hr]/gi, "[hr]");//not working ([[hr]][[hr]])
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]\n'));
});
});
The problem here is I dont know how to change dubble [hr][hr] for nothing, because this txt = txt.replace(/[hr][hr]/g, ""); not working, so would be cool for more explain about. One more time big thanks for answers! this function .replace is not as intuitive as in PHP.
EDIT: ahh.. I think is not possible to delete this dubel, because I extra insert it two times. Nvm. I will find and del this dubel in PHP.

How do I make text bold after the user clicks a button?

I am trying to make a text editor in JavaScript and it has various features like bolding the text and italics and some others. When the user clicks on any one of them, then anything that they have selected will become edited accordingly. Now I am able to get the selected text and even put strong tags before and after the text but when I do it the text doesn't get bold only the tags are seen. How can make the text bold? I sorry but I am unable to provide code since its too much and too messy. Thanks for reading query! Also if you know any JavaScript library which could help me solve this problem then you can suggest me.
document.getElementById("button").addEventListener("click",
() => {
let text = document.getElementById("text").innerText
let selection = window.getSelection();
let boldText = "<strong>" + selection + "</strong>"
document.getElementById("text").innerText = text.replace(selection, boldText)
})
<div id="text">
The dog barks and runs around.
</div>
<button id="button">Make selected text bold</button>
I am using inner text instead of inner html in order to reproduce the problem
You are using innerText to replace which is wrong as we want to change html so use innerHTML.
Code:
document.getElementById("button").addEventListener("click",
() => {
let text = document.getElementById("text").innerText
let selection = window.getSelection();
let boldText = "<b>" + selection + "</b>"
document.getElementById("text").innerHTML = text.replace(selection, boldText) //use innerhtml instead of innertext
})
<div id="text">
The dog barks and runs around.
</div>
<button id="button">Make selected text bold</button>
Here is some code that I used to change to inputted text on a button click
<input type="text" id="sign" value="">
<p style = "font-family: 'Dancing Script', cursive; font-size:50px;"
id="signOutput"></p>
<button onclick="signFunction()">Output Signature</button>
<script>
function signFunction() {var x = document.getElementById("sign").value;
document.getElementById("signOutput").innerHTML = x;
}
</script>
<p id="mypar">Hello</p>
<br>
<button type="button" onclick="changeStyle()">Click Me</button>
<script>
function changeStyle(){
var element = document.input
var element = document.getElementById("mypar");
element.style.fontWeight = "bold";
}
</script>

HTML/Javascript/jquery function Button to place comma at end of each line in TextArea

I currently have a little HTML window I use at work to automatically Capitalize All, Alphabetize, and Capitalize first letters of contents entered into a <TextArea> on the HTML. I was hoping to find a method to add an additional "Comma" Button (<input type="submit">) - so it will automatically add a comma to the end of each line in the <TextArea>.
This should do what you are trying to accomplish.
function comma(){
var textarea = document.getElementById('textarea').value;
var res = textarea.replace(/(\r\n|\n|\r)/gm,",\r\n");
console.log(res);
document.getElementById('textarea').value = res;
}
textarea {
width: 500px;
height: 500px;
}
<textarea id="textarea"></textarea>
<button onclick="comma()">Comma</button>
Steps
Put the content of the textarea in a variable, say 'textareaContent'
Find all occurrences of "\r\n" and replace with ";\r\n"
EDIT.
HTML + JS
<script>
function addComma()
{
// get textarea's content
var content = document.getElementById('myTextArea').value;
// replace all newline's with ';\n'
var replaced = content.replace(/\n/g,';\n');
// rewrite the content with the new content
document.getElementById('myTextArea').value = replaced; }
</script>
<textarea id='myTextArea' rows='5' cols='30'>
First Line
Second Line
Third Line
</textarea>
<input type='button' onclick='addComma()' value='Add Comma' />
Anyways, this is an example, in live action. See the fiddle here -- http://jsfiddle.net/u6b7yz21/
Cheers.

How to replace strike tag to input type text? [duplicate]

This question already has answers here:
Using jQuery to replace one tag with another
(13 answers)
Closed 9 years ago.
How to replacement strike element to input type text?
I have no idea at this time if any kind of solution please tell me here!
HTML Text :
In the <b>joy</b> of <strike>other</strike>, lies our <strike>own</strike>.
replace Text :
In the <b>joy</b> of <input type="text">, lies our <input type="text">.
If I understand your question well, you want this?
$('strike').each(function(){
$(this).replaceWith("<input type=\"text\" value=\"" + $(this).text() + "\" />");
});
jsfiddle: http://jsfiddle.net/M88u4/
Just add following jQuery statement
// search all strike element and replace it
$('strike').replaceWith(function(){
//create input element
var input = $('<input>',{
type: 'text',
value: $(this).html()
});
//replace with input element
return input;
});
Try this:
HTML
<div id="test">
In the <b>joy</b> of <strike>other</strike>, lies our <strike>own</strike>.
</div>
Javascript
$(function(){
var strikes = $('#test').children('strike');
var inputText = "<input type='text' />";
strikes.each(function(){
$(this).replaceWith(inputText);
});
});

Javascript: help with replacing '<div>' with '<br>' of an innerHTML!

I have an editable div where the user writes. As he writes, a javascript function adds the div html to a textarea. When the user presses SHIFT+Enter, the div gets a <br>. This is good.
But when the user presses Enter alone, the div gets <div></div> tags.
Therefore I try to make it so that when Enter is pressed, javascript scans the div's html to eliminate the </div> and change the <div> for <br>. The result will be that regardless of whether the user presses SHIF+Enter or Enter, the div's html will end up using only <br> for linebreaks.
<head>
<script type="text/javascript">
function doStuff(e){
if (window.event.keyCode == 13) {
var s=document.getElementById("divv").innerHTML;
s.replace("<div>", "<br>");
s.replace("</div>", "");
document.getElementById("divv").innerHTML=s;
}
document.getElementById("txtt").value = document.getElementById("divv").innerHTML;
}
</script>
</head>
<body>
<div contenteditable="true" id="divv" onKeyUp=doStuff(event);">
write here! Then press enter!
</div>
<textarea id="txtt" rows="30" cols="100">
</textarea>
</body>
My code doesn't work. When Enter is pressed, The textArea still shows div tags.
I'm not sure what I'm doing wrong. Please help.
The replace() method does not modify the string it's called on, it returns a new string with the occurrences replaced.
You can do something like:
var divv = document.getElementById("divv");
divv.innerHTML = divv.innerHTML.replace("<div>", "<br>").replace("</div>", "");
Usually browsers will have innerHTML store tags as <DIV> and </DIV> - you could try using:
s = s.replace(/<div>/ig,"<br>");
s = s.replace(/<\/div>/ig,"");
Firstly, if you use xhtml, you must use tag "< br / >".
Also draw attention on str.replace: it replaces only once.
js> var x = "hello";
js> x.replace("l", "L");
heLlo
Make your replace implementation:
js> function myreplace(str, pattern, change_to) {
var s = str;
var s2 = s;
do {
s2 = s;
s = s.replace(pattern, change_to);
} while (s2 != s);
return s;
}
js> myreplace("helllllo", "l", "L");
heLLLLLo

Categories

Resources