Javascript event listener behavior - javascript

I added a listener to an unordered list to perform a function when a text area element within the ul was changed. When the text area is changed, I wanted to get the value of the now changed text area, and save it. When I try to save the value in newNotes, I am given back the INITIAL value of the text area, not the value after the text area has been changed. Isn't that the whole point of the listener, to be triggered upon a change?
ul.addEventListener('change',(e)=> {
if(e.target.tagName === "TEXTAREA") { // if the ul was changed and a textarea was targeted
const li = e.target.parentNode; // the parent list item of the text area
const liName = li.firstChild.textContent; // this is a string
var newNotes = e.target.textContent; // PROBLEM : RETURNS WRONG VALUE
console.log(newNotes);
updateNotesTo(liName, newNotes); // regarding localStorage
}
});

You want the value from textarea
Change
var newNotes = e.target.textContent;
To
var newNotes = e.target.value;

You have to use the .value attribute.
var newNotes = e.target.value;
See also, Textarea.textcontent is not changing

Related

The value of input is not being assigned to a div

I want to get the text from the text area (id= getText), and than assign its value to the new div that I have created but the value is not being saved inside that new div.. I have tried many times but the value of the input is not saved and there is not change in when I click the button
let getText = document.getElementById("getText"); // this is textarea
let select = document.getElementById("selectBtn"); //this is button
//this is another div
let result = document.getElementById("result");
let new_p = document.createElement("div"); //creating element
new_p.innerHTML = "";
result.appendChild(new_p); // adding into resut div
//getting inner text of the input
let value = new_p.innerText;
//adding an event listener
select.addEventListener("click", function(e) {
e.preventDefault();
new_p.innerHTML = value;
//it does not works and the value is not saved
})
let getText = document.getElementById("getText"); // this is textarea
let select = document.getElementById("selectBtn"); //this is button
//this is another div
let result = document.getElementById("result");
let new_p = document.createElement("div"); //creating element
new_p.innerHTML = getText.value;
result.appendChild(new_p); // adding into resut div
//getting inner text of the input
let value = new_p.innerText;
//adding an event listener
select.addEventListener("click", function(e) {
e.preventDefault();
new_p.innerHTML = getText.value;
console.log(value)
//it does not works and the value is not saved
})
Replace new_p.innerHTML = ""; for
new_p.innerHTML = getText.value
and inside of click event,
new_p.innerHTML = getText.value;
Moving forward, try to use online code editors,
to post your code, Since it might be easier for anyone to assist you, Be aware to remove any personal info from the code.
Here is a fiddle with your code https://jsfiddle.net/k8b24n3q/12/
The reason was not working, was because you were setting on click event an undefined value.

Access HTML TextArea data with JavaScript in real time to find and change data being typed in real-time

I am writing an html page with a form to collect textarea data. As I type, I would like for a JavaScript program to watch for special characters such as "\n - newline", a "\t-tab", or other items I am watching for and change the text in the textarea immediately. I got it partially working with the textfield.value function.
Thanks for the help.
You can add an onChange or onInput event listener to the text area.. Whenever there is a change in the value of the text area, the function passed to the listener is fired
Add onChange or onInput event listener. That's how you can do it.
let textarea = document.querySelector("textarea");
textarea.addEventLisenter("input", e => {
// Text in your textarea;
let value = e.target.value;
// to change your text area input
let newValue = e.target.value.replace(/some regex/, "new value");
e.target.value = newValue;
})
You can add InputEvent handler to the text area.
let textArea = document.getElementById("the-id");
textarea.addEventListener("input",event=>{
let newText = event.data;
swicth(newText){
case "'\n" : {
/* Your logic here */
}
}
});

How to copy a calculated value to clipboard?

I've got a formula that calculates a value. This value I want to insert to an Excel sheet. To make it comfortable to the user I want to put it to the clipboard automatically.
I try to do my first steps in JS and encountered this (probably) very simple problem. But all methods I found are related to raw values of html input-tags. I never have seen any copy-to-clipboard functions from values created in js.
var EEFactor = 1*1; // just a formula to calculate a value
copyValue2Clipboard(EEFactor);
function value2Clipboard(value) {
// please help
}
There is an example with a great explanation here
Try like this.
function copyToClipboard(str) {
var el = document.createElement('textarea');
// Set value (string to be copied)
el.value = str;
// Set non-editable to avoid focus and move outside of view
el.setAttribute('readonly', '');
el.style = {position: 'absolute', left: '-9999px'};
document.body.appendChild(el);
// Select text inside element
el.select();
// Copy text to clipboard
document.execCommand('copy');
// Remove temporary element
document.body.removeChild(el);
};
var EEFactor = 1*1;
copyToClipboard(EEFactor);
const copyToClipboard = str => {
const el = document.createElement('textarea'); // Create a <textarea> element
el.value = str; // Set its value to the string that you want copied
el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof
el.style.position = 'absolute';
el.style.left = '-9999px'; // Move outside the screen to make it invisible
document.body.appendChild(el); // Append the <textarea> element to the HTML document
const selected =
document.getSelection().rangeCount > 0 // Check if there is any content selected previously
? document.getSelection().getRangeAt(0) // Store selection if found
: false; // Mark as false to know no selection existed before
el.select(); // Select the <textarea> content
document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events)
document.body.removeChild(el); // Remove the <textarea> element
if (selected) { // If a selection existed before copying
document.getSelection().removeAllRanges(); // Unselect everything on the HTML document
document.getSelection().addRange(selected); // Restore the original selection
}
};

Simulate cut function with JavaScript?

I'm working on a chrome extension and I want to do something with the text that is selected (highlighted by the user) on the page. For that, I need a way to remove the selected text, for example text inside an input field.
I found a way to "clear" the selected text, meaning it will be unselected:
Clear Text Selection with JavaScript But it doesn't seem to be what I'm looking for.
This just removes the highlighting from the text:
window.getSelection().empty();
I want to remove the text that is selected, if it's editable text. Is this possible with JavaScript?
You can use the deleteFromDocument method:
window.getSelection().deleteFromDocument()
This will immediately remove the selected content from the document, and as such also clear the selection.
As described formally in the MDN web docs:
The deleteFromDocument() method of the Selection interface deletes the selected text from the document's DOM.
If you'd like to be able to delete text from input elements instead, you need to use different APIs:
var activeEl = document.activeElement;
var text = activeEl.value;
activeEl.value = text.slice(0, activeEl.selectionStart) + text.slice(activeEl.selectionEnd);
Edit from me, Synn Ko: to cover input fields, textareas and contenteditables, use this:
var selection = window.getSelection();
var actElem = document.activeElement;
var actTagName = actElem.tagName;
if(actTagName == "DIV") {
var isContentEditable = actElem.getAttribute("contenteditable"); // true or false
if(isContentEditable) {
selection.deleteFromDocument();
}
}
if (actTagName == "INPUT" || actTagName == "TEXTAREA") {
var actText = actElem.value;
actElem.value = actText.slice(0, actElem.selectionStart) + actText.slice(actElem.selectionEnd);
}

Why is this textfield losing focus with morphdom?

Here's a contrived example below that isolates my problem. There's a simple text field w/ a message that displays if the character count is even. If I move the message below the textfield it seems morphdom sees that only the value of the textfield has changed, so it doesn't rebuild the input node which mean the control keeps focus. If I keep the message above the textfield, morphdom rebuilds the control despite the fact that I'm specifying an id.
From the docs...
https://github.com/patrick-steele-idem/morphdom
In addition, the algorithm used by this module will automatically match up elements that have corresponding IDs and that are found in both the original and target DOM tree.
Code Example...
https://codepen.io/anon/pen/NOvZJz
var text = "";
var origRootDiv = null;
function createView() {
var rootDiv = document.createElement("div");
// If moved under, issue goes away
if (text.length > 0 && text.length % 2 == 0) {
var messageDiv = document.createElement("div");
messageDiv.innerHTML = "Even char count!";
rootDiv.appendChild(messageDiv);
}
// End if
var input = document.createElement("input");
input.id = "this-should-help-right";
input.value = text;
rootDiv.appendChild(input);
input.addEventListener("input", function(e) {
text = e.target.value;
var newRootDiv = createView();
morphdom(origRootDiv, newRootDiv);
});
return rootDiv;
}
origRootDiv = createView();
document.body.appendChild(origRootDiv);
EDIT
The current behavior is that if you type 1 character in the field the text field retains focus (good), but if you type a second character in the field and the "Even char count!" message is shown the textfield loses focus (bad).
The desired behavior is that even if the message is shown, the textfield should retain focus.
Add .focus() to the input by using id.
see this https://www.w3schools.com/jsref/met_text_focus.asp
Solution
See the updated code,
input.addEventListener("input", function(e) {
text = e.target.value;
var newRootDiv = createView();
morphdom(origRootDiv, newRootDiv);
// added the input with Id here
document.getElementById('this-should-help-right').focus();
});
I have added document.getElementById('this-should-help-right').focus(); after morphdom call. So i think the problem is solved

Categories

Resources