HTML/Javascript - How to display text from input field as HTML code? - javascript

I have a textarea on my webpage that users will enter HTML code in. I want to display that HTML code somewhere else on my webpage. How do I got about this?
Essentially I want to do what stack overflow does in their question asking text area where you can enter in HTML tags like strong and they will display appropriately like this when the text is displayed. Another example is that the user might enter an image tag and I would want that image to display in another part of the site.
I am using Node and Express on the backend with MongoDB to store the user input and ejs templates to display the HTML.

$("#htmlinput").on("input",function(){
$("#target").html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="htmlinput"></textarea>
<div id="target"></div>

on js
function write() {
var text = document.form.input.value;
return document.getElementById('id').innerHTML = text;
}
on html
<form name="form">
<textarea onkeyup="write()" name="input"></textarea>
<div id="id"></div>
</form>

Below is my code. In my JS, I get the value from the textarea and displayed it to the div element with an id of output by using .innerHTML property. This property sets or returns the HTML content (inner HTML) of an element.
function myInput(){
var y = document.getElementById('textarea').value;
document.getElementById('output').innerHTML = y;
}
*{ box-sizing: border-box; }
textarea{ width: 100%; }
#output{
display:block;
background:#489ae0;
color: #fff;
margin: 0;
padding: 10px 20px;
box-sizing: border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" placeholder="please input your texts here" oninput="myInput()"/></textarea>
<div id="output"></div>

Related

Displaying text in textarea with formatting in place (e.g. <br>)

How can I display a wall of text example:
hello
<br>
how is your day
<br>
123
Into
hello
how is your day
123
I'm trying to display these into a textarea field as well.
I've tried with this
$('<textarea />').html(theString).text(); but it does not display my desired result
Edit:
Current code:
function displayCustom (data) {
var myString= data.getAttribute("data-contentDetails");
$('#textareaContent").html(myString);
}
this is not possible to do this with textarea. you can use content editable div
var theString = `Hello.<br>Hi.<br>Hey, <strong>user</strong> <span style="color: red">Logout</span>.`
// in pure js
document.getElementById('textareaContent').innerHTML = theString;
// OR in jQuery
$('#textareaContent').html(theString)
div {
width: 250px;
height: 150px;
border: 1px solid #ababab;
padding: 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="textareaContent" contenteditable="true"></div>
UPDATE
if you have to use textarea and just need to use <br /> (you couldn't use another HTML tag as a text) you can use:
var myString = `Hello<br>Hi<br>Hey, use`
$('#text').html(myString.replace(/<br>/g, '\n'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="text"></textarea>
Use a Div with a contenteditable attribute if you want the user to edit the displayed new format. Try to append or insert this.
For a textarea
$('<div contenteditable="true" />').html(theString);
Just remove the contendeditable="true" attribute if you just want to display the new format.

Why does my script not make new lines using keyup?

I'm coding a script for my forum which generates a preview of the given string.
Here is my js code
function MakePreview() {
var getText = document.getElementById('inputText').value;
document.getElementById('outputText').innerHTML = getText;}
Here is my HTML code
<article>
<h2>What are you doing?</h2>
<textarea id="inputText" onkeyup="MakePreview()"></textarea>
<br/>
<input type="submit" class="button" value="Hello"/>
</article>
<article>
<p id="outputText"></p>
</article>
Furthermore I have an textarea for the input and an paragraph for the output. But the output does not make a new line like textareas does.
Usually a paragraph makes automatically new lines when the string is longer than the width of the given content.
Does someone have a solution?
Thanks in advance
I'm not sure, if it's possible to achieve exactly what you want (due to the different font size and family), but this snippet is very close to it.
function makePreview() {
var text = document.getElementById('inputText').value;
document.getElementById('outputText').innerHTML = text;
}
.wrapper {
width: 150px;
}
.wrapper textarea {
width: 100%;
}
#outputText {
position: relative;
white-space: pre-wrap;
word-break: break-all;
border: 1px solid #ccc;
}
<div class="wrapper">
<textarea id="inputText" oninput="makePreview()"></textarea>
<p id="outputText"></p>
</div>
The idea is to wrap both the textarea and the p within a same parent to get their widths to match. word-break: break-all and white-space: pre-wrap "copies" the automatic text wrapping and entered new-lines within textarea to the p element.
However, the text might be cutted in a different place, depending on the used font family and size. You could get a better match if you'd use the same font in both elements.
You can instruct paragraph to respect new lines characters (and other whitespaces like tabs, spaces, etc.) by setting its white-space property to pre:
function MakePreview() {
var getText = document.getElementById('inputText').value;
document.getElementById('outputText').innerHTML = getText;
}
#outputText {
white-space: pre;
}
<textarea id="inputText" onkeyup="MakePreview()" rows="4" cols="20"></textarea>
<p id="outputText"></p>
In html multiple whitespaces are replaced by single space so if you want to preview in paragraph you need to replace newlines with <br/>
function MakePreview() {
var getText = document.getElementById('inputText').value;
document.getElementById('outputParagraph').innerHTML = getText.replace('\n', '<br/>');
}
Use wrap="hard" on your textArea. It will help for new line if the length is more the textArea size.
For fixed row and column you can use rows="2" cols="20" in textarea.

Javascript to dynamically add textbox , and again convert the text box to text

I need something like a fill in the blanks sheet for children. When people click the ------ (dashes) it should turn into a textbox, and people can type it. after that when they move from that element after typing, it should turn into the text that they entered inside that text box.
I really dono how to approach this problem. I tried the following code, but what happens is, i am unable to type inside the text box. The cursor is not appearing at all
<html>
<head>
<title>NSP Automation</title>
<script src ="jquery.min.js">
</script>
</head>
<body>
<div class="container">
My Name is = <span id="name">__________<span>
</div>
<script>
$(document).on('click', '#name', function(){
document.getElementById("name").innerHTML = "<input type=\"text\">";
});
</script>
</body>
</html>
any pointers on how to achieve this ?
Thanks,
Since you've set the listener on the whole document, you will be recreating the input-tag with every click. Try something like:
$('#name').on('click', function(){
this.innerHTML = "<input type=\"text\">";
$('#name').off('click')
}
After clicking on the span-element, you remove the listener on it again, and you should be able to type.
http://jsfiddle.net/218rff9v/
Here is an example that generates the wished behaviour for all spans in your container. Some details can be improved but I think it's working as expected.
function convertSpanToInput() {
// Insert input after span
$('<input id="tmp_input">').insertAfter($(this));
$(this).hide(); // Hide span
$(this).next().focus();
$("#tmp_input").blur(function() {
// Set input value as span content
// when focus of input is lost.
// Also delete the input.
var value = $(this).val();
$(this).prev().show();
$(this).prev().html(value);
$(this).remove();
});
}
$(function() {
// Init all spans with a placeholder.
$(".container span").html("__________");
// Create click handler
$(".container span").click(convertSpanToInput);
});
Here is an html example with which you can test it:
<div class="container">
My Name is = <span></span>. I'm <span></span> years old.
</div>
JsFiddle: http://jsfiddle.net/4dyjaax9/
I'd suggest you have input boxes and don't do any converting
Simply use CSS to remove the borders and add a dashed border bottom
input[type=text]{
border:none;
border-bottom:1px dashed #777;
} <!-- something like that -->
add a click handler to add a edited class, so you can remove the bottom border
input[type=text].edited{
border:none;
}
That way you don't need to replace html elements, you just style them to look different
Why not use text input and only change CSS classes?
CSS:
.blurred{
border-style: none none solid none;
border-width: 0px 0px 1px 0px;
border-bottom-color: #000000;
padding: 0px;
}
.focused{
border: 1px solid #999999;
padding: 3px;
}
JavaScript:
$('#nameInput').focus(function(){
$(this).removeClass('blurred').addClass('focused');
});
$('#nameInput').blur(function(){
$(this).removeClass('focused').addClass('blurred');
});
HTML:
<div class="container">
My Name is = <span id="name"> <input id="nameInput" type="text" class="blurred"></input> <span>
</div>
Check this jsfiddle:
http://jsfiddle.net/gwrfwmw0/
http://jsfiddle.net/we6epdaL/2/
$(document).on('click', '#name', function(e){
if( $("#myText").is(e.target))
return;
$(this).html("<input type='text' id='myText' value='"+ $(this).html() +"'>");
});
$(document).on("blur", "#name", function(){
$(this).html( $("#myText").val() );
});

How to remove "no file selected" from type=file inputs?

I can't seem to figure out any way to remove the "No file selected" text that shows up next to inputs of type "file".
Do you guys know any way how to remove this text?
input[type='file'] {
color: transparent;
}
Enjoy
There is no cross-browser way to do this. The "no file selected" text is in the implementation-defined part of the widget, and I don't believe that most browsers offer much in the way of browser-specific customization. On the other hand, you could simply use CSS to cover the text with something when the value attribute is empty.
You can do this by defining a width to the input and hiding the exceeding content (the undesired "No file selected" text).
input {
width: 132px;
overflow:hidden;
}
Here is the demonstration on jsfiddle.
Beware: each language has its own default text and it may render different input sizes. In brazilian portuguese that 132px width is fine!
My answer was based on this similar question on stackoverflow.
You can replace the file field with a button with the answer to this question: file upload button without input field?
CSS
<style>
#image_file{
position: relative;
width: 188px;
border: 1px solid #BBB;
margin: 1px;
cursor: pointer;
float: left;
}
</style>
HTML
<input id="image_file" onclick="getFile()" onfocus="this.blur()" value=""/>
<div style='height: 0px;width: 0px; overflow:hidden;'>
<input type="file" id="PinSpot_file">
</div>
<input type="button" onclick="getFile()" style="background-color: #DDD;" value="Browser" >
JAVASCRIPT
function getFile(){
document.getElementById("PinSpot_file").click();
}
// Event when change fields
$('#PinSpot_file').live('change', function(e) {
var file = this.value;
var fileName = file.split("\\");
document.getElementById("image_file").value = fileName[fileName.length-1];
//AJAX
}
This is a really good hack and its a lot cleaner.
HTML
<div id="file_info' style='display:inline;'>Browse</div>
<input type="file" name='file[]' multiple style='opacity: 0;' onchange='displayFileName()'/>
JS
function displayFileName() {
var files = $('input[type="file"]')[0].files;
document.getElementById('file_info').innerHTML = files.length + " images to upload";`
}
Well, since there is no way to completely disable the text, I'd suggest either placing an element over the text or try the following solution..
CSS
input[type="file"] {
width: 90px; /* Keep it under 100px in order to hide the unwanted text. */
}
and add an html inline-title attribute to the element to hide the "No File Chosen" hover text.
HTML
<input type="file" id="FileId" title="">
or, you could do it all with JavaScript.
JS
document.addEventListener('DOMContentLoad', myFunction);
function myFunction() {
const FilePicker = document.getElementById('FileId');
FilePicker.style.width = "90px";
FilePicker.title = ""; // Leave This Empty
}
You can try this. Its work for me firefox browser
<style type="">
input[type='file'] {
color: transparent;
}
</style>

Showing the contents of a SPAN using JavaScript

I have this code. I've done this for years now but I'm stumped with the result of this example. The purpose is to make the text box visible and put the contents of the clicked SPAN tag in it.
document.onclick = CaptureClickedElement;
function CaptureClickedElement(e)
{
var EventElement;
if(e==null)
EventElement = event.srcElement;// IE
else
EventElement = e.target;// Firefox
if( EventElement.tagName == "SPAN")
{
document.getElementById("divTXT").style.display="";
document.getElementById("txt").value = document.getElementById("Span1").innerHTML;
alert(document.getElementById("Span1").innerHTML)
}
}
Strangely though, it DOES show the contents but also shows open/close SPAN tags at the end of it. If I alert ther results, the same thing is shown.
Please find the attached screen shot of it here.
Does anyone have an idea of why this is happening?
Thanks!
Here is the HTML (copied from comments by mplungjan)
<style type="text/css">
#divOuter {
width: 100px;
height: 70px;
border: 1px solid blue;
float: left;
}
</style>
<body>
<div>
<form name="frm" method="post" action="">
<div id="divTXT" style="display:none">
<input type="text" id="txt" name="txt" value="" size="30" />
</div>
</form>
</div>
<div id="divOuter">
<span id="Span1">hi, this is a test.<span>
</div>
</body>
Structure problem:
<span id="Span1">hi, this is a test.<span>
Note the absence of a proper close to the span.
Need to use .innerText (for IE) and .text for others.

Categories

Resources