How to output a textarea in HTML to a variable in Javascript? - javascript

In a HTML website I have a textarea created like this:
<textarea id = "myTextArea" rows = "30" cols = "80"></textarea>
I would like after something is written in the text area, for that text to be sent to a variable in javascript.
I have tried doing this, but it did not work:
var x = document.getElementById("myTextArea").value;
The console.log(x); gives back nothing, not null, just empty space. However, if I log out console.log(document.getElementById("myTextArea").value) then I get the text that I have written in my textarea.
Why does var x = document.getElementById("myTextArea").value; not work?
My Javascript:
<script>
var x = document.getElementById("myTextArea").value;
const regex = /([a-z]+)/;
const match = regex.exec(x);
var intervalID = window.setInterval(myCallback, 500); <!-- Calls every 5s -->
function myCallback() {
if(match){
const name = match[1];
console.log(name);
}
else{
console.log('no match');
console.log(match);
}
}

To achieve this, you can register an event listener on your textarea:
var textArea = document.getElementById('myTextArea');
textArea.addEventListener('input', function(event){
console.log(event.target.value);
});
The listener listens for any input events on your textara and logs the value of your textarea as the value changes.
Here's a live demo for your quick reference.

You will need to use onkeyup and onchange for this. The onchange will prevent context-menu pasting, and the onkeyup will fire for every keystroke.
See my answer on How to impose maxlength on textArea for a code sample.

In my example, the variable is the text variable. This variable is filled with the text of the text by clicking on the button.
Was it necessary?
var x = document.getElementById("myTextArea");
var button = document.querySelector("button");
var text = "";
button.onclick = function() {
text = x.value;
console.log(text);
}
#myTextArea {
width: 100%;
height: 100px;
}
<textarea id="myTextArea" rows="30" cols="80"></textarea>
<button>Check variable with text</button>
Second example using oninput event.
var x = document.getElementById("myTextArea");
var text = "";
x.oninput = function() {
text = this.value;
console.log(text);
}
#myTextArea {
width: 100%;
height: 100px;
}
<textarea id="myTextArea" rows="30" cols="80"></textarea>

Related

Changing color of a certain word in a paragraph using js

$('#txtInput').keyup(function(){
var txtInput = $(this).val();
localStorage.setItem('inputData', txtInput);
var returnData = localStorage.getItem('inputData');
$('#txtInput').val(returnData);
var hasTest = returnData.includes("<h1>");
if(hasTest == true){
}
});
I'm creating a text editor using js.Here I'm using localStorage to store data and retrieve data.I need to add highlighting syntax feature.
For example : If 'h1' found from the text, color the 'h1' to red.I used ".includes() and it finds the word but I have no idea how to change the color of the found text.I really appreciate your help
Try this solution:
1. Use a contenteditable element instead of input or textarea.
<div id="txtInput" contenteditable></div>
The reason is we need to display HTML with CSS inside of this input area.
2. Filter the result with highlight text.
// get highlight text from string
const highlighten = (string, highlight) => {
string = stripHtml(string);
// add highlight
if (string.includes(highlight)) {
string = string.replaceAll(highlight, `<span style="color:red">${highlight}</span>`);
}
return string;
};
Use replaceAll to set the highlight CSS. You can see the stripHTML() which is for cleaning the string before doing the filter.
3. Handle keyup event
// on keyup event
$('#txtInput').on('keyup', function(e) {
const $input = $(e.currentTarget);
// you can manage your localStorage data here
// ...
// filter the input
$input.html(highlighten($input.html(), 'h1'));
// set caret
setCaretAtTheEnd($input.get());
});
As we replace the #txtInput with the new result, we will lose the caret position, that's why we need setCaretAtTheEnd() to set the caret back to the end of input.
// https://stackoverflow.com/questions/822452/strip-html-from-text-javascript
function stripHtml(html) {
let tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
// https://stackoverflow.com/questions/6249095/how-to-set-the-caret-cursor-position-in-a-contenteditable-element-div
function setCaretAtTheEnd(el) {
var range = document.createRange()
var sel = window.getSelection()
const nodes = el[0].childNodes;
let offset = 0;
nodes.forEach((node, i) => {
offset = node.length || 1;
});
range.setStart(nodes[nodes.length - 1], offset)
range.collapse(true)
sel.removeAllRanges()
sel.addRange(range)
}
// get highlight text from string
const highlighten = (string, highlight) => {
string = stripHtml(string);
// add highlight
if (string.includes(highlight)) {
string = string.replaceAll(highlight, `<span style="color:red">${highlight}</span>`);
}
return string;
};
// on keyup event
$('#txtInput').on('keyup', function(e) {
const $input = $(e.currentTarget);
// you can manage your localStorage data here
// ...
// filter the input
$input.html(highlighten($input.html(), 'h1'));
// set caret
setCaretAtTheEnd($input.get());
});
#txtInput {
width: 400px;
height: 200px;
border: 1px solid #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="txtInput" contenteditable>
</div>
This should do it for you:
if (hasTest == true) {
returnData = returnData.replace('<h1>', '<h1 style="color:red">')
$('#txtInput').val(returnData);
}

How to make a certain part of textarea read-only

I have a text area and I dynamically add data to it and it works fine. What I wanted to achieve was after the data is appended that data cant be altered (edited) but after the last element of the data user can start typing on the textarea. I was thinking of maybe calculating the length of string data the set read-only to that part. How can I achieve this? Any help is appreciated. Thanks in advance.
For a visual example take a look at the terminal of this website: https://www.online-python.com/
function test() {
x = 'this is a string to be appended to text area'
document.getElementById("textArea").value = x;
}
<textarea id="textArea"></textarea>
<button onclick="test()">Append</button>
You can add a keydown event listener that checks whether the selectionStart is smaller than the length of the textarea's value minus the length of the string appended:
let x = 'this is a string to be appended to text area'
var hasAppended = false;
function test() {
hasAppended = true
document.getElementById("textArea").value = x;
}
textArea.addEventListener('keydown', function(e) {
if (hasAppended) {
if (this.selectionStart > this.value.length - x.length && this.selectionStart != this.value.length) {
e.preventDefault()
e.stopPropagation()
}
}
})
<textarea id="textArea"></textarea><button onclick="test()">Append</button>
It is not possible to selectively mark parts of a <textarea> read-only, however, a similar effect can be achieved with contenteditable elements:
function test() {
const x = 'this is a string to be appended to text area'
const span = document.createElement('span')
span.appendChild(document.createTextNode(x))
span.setAttribute('contenteditable', 'false')
document.getElementById("textArea").appendChild(span);
}
#textArea{
border: 1px solid black;
height: 50px;
}
<div id="textArea" contenteditable="true"></div>
<button onclick="test()">Append</button>
However, this will still allow the user to delete the read-only block, or write before it.
This almost works.
EDIT:
Improved it a bit by changing keydown to keyup.
Now there is no need for space at the end of the read-only text and CTRL+a and then backspace will make the text come back almost instantly.
Maybe you can improve on it.
window.onload = function() {
document.getElementById('textArea').addEventListener('keyup', function (e){
var readOnlyLength = parseInt(document.getElementById("textArea").getAttribute('data-readOnlyLength') );
var currentLength = parseInt(document.getElementById("textArea").value.length );
if (readOnlyLength >= currentLength ) {
document.getElementById("textArea").value = document.getElementById("textArea").getAttribute('data-readonly') ;
}
}, false);
};
function test() {
x = 'this is a string to be appended to text area'
document.getElementById("textArea").value = x;
document.getElementById("textArea").setAttribute('data-readonly' , x);
document.getElementById("textArea").setAttribute('data-readOnlyLength' , x.length);
}
<textarea id="textArea"></textarea>
<button onclick="test()">Append</button>

Keydown Event to save locally using javascript

I am making a basic online editing interface for coursework. I would like to save the content of my #textarea div every time there's a keydown event. The code works partially but I can't edit the text without the cursor going to the top of the div.
document.addEventListener('keydown', saveLocally);
const saveLocally = function() {
let areaText = document.getElementById("textArea");
console.log(areaText);
let text = document.getElementById("textArea").innerHTML;
console.log(text);
let localData;
localStorage.setItem('siteData', text);
localData = localStorage.getItem('siteData');
console.log(localData);
console.log(localStorage.getItem('siteData'));
areaText.innerHTML = localData;
}
<div id="inputArea">
<div id="textArea" contenteditable="true"></div>
</div>
The issue is because you immediately update the innerText of the element after someone types. This affects the cursor as the node contents are changed. You don't need to do this anyway, so the line can be removed.
You instead need to perform the logic which retrieves the value from localStorage when the page loads. Also note that you should use the keyup event instead of keydown, otherwise you'll not save the last key which was pressed. Try this:
<div id="inputArea">
<div id="textArea" contenteditable="true"></div>
</div>
let areaText = document.getElementById("textArea");
const saveLocally = function() {
let text = areaText.innerHTML;
localStorage.setItem('siteData', text);
}
const retrieveSavedText = function() {
var text = localStorage.getItem('siteData');
areaText.innerHTML = text;
}
document.addEventListener('keyup', saveLocally);
retrieveSavedText();
Working example

replacing html tag inside textarea with text

code :
<script src="Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var $this = $("#Test_txtarea");
var txtval = $this.val();
$this.find("img").each(function () {
var imgbytes = $(this).attr("name"); // extract bytes from selected img src
$(this).replaceWith(imgbytes);
});
$("#NewVal").html(txtval);
});
</script>
html
<textarea ID="Test_txtarea" >Hi <img src='test.png' name='test' > kifak <img src='test2.png' name='test1' > Mnih <img src='test3.png' name='test3' ></textarea>
<span id="NewVal" ></span>
what i am trying to do is basically trying to replace each img tag by it's name so the final textarea value will be like this : Hi test kifak test1 Mnih test3
this is the jsfiddle : http://jsfiddle.net/Ga7bJ/2/
the .find("img") always return 0 as length.how can i fix this code ?
Though it is not complete answer or at least not going to be "Copy paste" answer, there is few things you need to do here:
The content of Textarea is VAL of it and not InnerHTML. So, you have to pick that content as value and than create a hidden div and put it as HTML. Once you did it, you can now find the HTML tags in it using find rather easily.
Once you find tag you can find the name using attr() function
Once you have name, than you again go back to val() of textarea, and do regex replace or using HTML you can replace as well I guess, but not sure.
Look at this jsFiddle. What is does is:
It gets the value from your Test_txtarea and sets that as the html of a hidden div.
The hidden div wil render the images within the textarea.
After they have been rendered, I find these images,
- get the source,
- remove all characters after the .
- replace the entire html of the image with the src.
After all that has been done you are left with a div with the value you wanted.
All what is done next is the html from the div is copied to the value of your textarea.
function replaceImageWithSrc(value){
var div = $("#invisible");
div.html(value);
var images = div.find("img");
images.each(function(index){
var src = $(this).attr("src").split(".")[0];
this.outerHTML = src;
});
return div.html();
}
$(document).ready(function () {
var txtArea = $("#Test_txtarea");
var txtval = txtArea.val();
txtval = replaceImageWithSrc(txtval);
txtArea.val(txtval);
});
The following code works for me. Basically, I get the value of the text area and append it to an off-screen div. Now that I have valid markup nesting, I can iterate the child-nodes as normal.
function byId(e){return document.getElementById(e)}
function newEl(t){return document.createElement(t)}
function test()
{
var div = newEl('div');
div.innerHTML = byId('Test_txtarea').value;
var msg = '';
var i, n = div.childNodes.length;
for (i=0; i<n; i++)
{
if (div.childNodes[i].nodeName == "IMG")
msg += div.childNodes[i].name;
else if (div.childNodes[i].nodeName == "#text")
msg += div.childNodes[i].data;
}
byId('NewVal').innerHTML = msg;
}

Change div on input (live & pass variable)

I want a div that shows your input, but for example * 2.
I also want it to happen as you type. So it has to be 'live'.
I found a lot of 'on keyup' jquery functions but I need to change the 'variable' that is typed in the input field.
So for example:
<input id="input" /> (types 4)
<div class="showinputhere"> (shows 8) </div>
How do I do this, it has to happen immediately when you type.
Use this
$(document).ready(function()
$('input').keyup(function(){
$('.showinputhere').html(parseInt($(this).val(),10) *2);
});
});
JSFiddle -> http://jsfiddle.net/gLExt/
try the following code:
<script>
function calVal(inputVal){
var input = document.getElementById("input");
var div = document.getElementsByClassName("showinputhere");
div = div[0];
div.innerHTML = inputVal * 2 == 0 ? "" : inputVal * 2;
}
</script>
And call the function "onkeyup" event of input like this:
<input id="input" onkeyup="calVal(this.value);"/>
var input = document.getElementById("input");
var div = document.getElementsByClassName("showinputhere");
div = div[0];
input.addEventListener("change", function() {
div.innerHTML = this.value * 2;
})
That's untested, but might work.
Here's an edited version using keyup, because I've been informed that change does not auto-update.
var input = document.getElementById("input");
var div = document.getElementsByClassName("showinputhere");
div = div[0];
input.addEventListener("keyup", function() {
div.innerHTML = this.value * 2;
})

Categories