I am trying to hide and show the innerHTML of a textarea based on focus and blur. Its working well. But an issue is, when i delete the entered text the inside innerHTML is already there in the element but its not showing. Following is the issue replication steps:
Enter text inside the textarea
Select all the text and delete it
Then mouseout from the textarea
The innerHTML is not visible there in the browser
But innerHTML is visible in the elements when i check with browser inspect element
let textarea = document.querySelectorAll("textarea");
for (i = 0; i < textarea.length; i++) {
let innertext = textarea[i].innerHTML;
textarea[i].addEventListener("focus", (e) => {
e.target.innerHTML = "";
})
textarea[i].addEventListener("blur", (e) => {
e.target.innerHTML = innertext;
})
}
<textarea name="" id="" cols="30" rows="10">Test</textarea>
Use .value instead of .innerHTML to change/retrieve the value of the textarea. The innerHTML property does not update in the browser once a change has been made to the textarea's content.
let textarea = document.querySelectorAll("textarea");
for (i = 0; i < textarea.length; i++) {
let innertext = textarea[i].innerHTML;
textarea[i].addEventListener("focus", (e) => {
e.target.value = "";
})
textarea[i].addEventListener("blur", (e) => {
e.target.value = innertext;
})
}
<textarea name="" id="" cols="30" rows="10">Test</textarea>
This solution is using placeholder:
<textarea name="" id="" cols="30" rows="10" placeholder='Test'></textarea>
let textarea = document.querySelectorAll("textarea");
for(i=0;i<textarea.length;i++) {
let innertext = textarea[i].placeholder;
textarea[i].addEventListener("focus",(e)=>{
console.log( e.target.placeholder);
e.target.placeholder = '';
});
textarea[i].addEventListener("blur",(e)=>{
e.target.placeholder = innertext;
})
}
Related
I'm building a virtual keyboard with vanillla javascript but don't know where to add the onclick event listener to the buttons or how to grab them. I have a printKeys function that loops thru the array and prints them onload, and I have an unfinished typeKeys function where I'm trying to grab the innerhtml and print it to the input field.
HTML
</head>
<body onload="printKeys()">
<div class="text">
<input type="text" class="your-text" id="input" placeholder="Your text here.."></input>
<button class="copy-btn">Copy</button>
</div>
<div class="keyboard" id="keyboard"></div>
<script src="index.js"></script>
</body>
</html>
Javascript
const alphaKeys = ["a","b","c"];
const numKeys = "1234567890";
const keyboard = document.getElementById("keyboard");
// render keyboard
function printKeys() {
for (let i = 0; i < alphaKeys.length; i++) {
let keys = document.createElement("button");
keys.innerHTML = alphaKeys[i];
//add onclick function to button
keyboard.appendChild(keys);
}
}
//onClick event, add text in text field
const input = document.getElementById('input')
function typeKeys() {
console.log("clicked")
//grab input and replace with button innerhtml
}
Instead of adding the event handler to each button, you can apply it to the parent (keyboard) then just use the event's target to get the specific button. I also added the character to a data-attribute instead of the innerHTML.
const alphaKeys = ["a","b","c"];
const numKeys = "1234567890";
const keyboard = document.querySelector(".keyboard");
// render keyboard
function printKeys() {
for (let i = 0; i < alphaKeys.length; i++) {
let keys = document.createElement("button");
keys.innerHTML = alphaKeys[i];
keys.setAttribute("data-character",alphaKeys[i]);
keyboard.appendChild(keys);
}
}
//onClick event, add text in text field
const input = document.getElementById('input')
function typeKeys(character) {
input.value += character;
}
keyboard.addEventListener("click",function(e){
let target = e.target;
if(target.getAttribute("data-character")){
typeKeys(target.getAttribute("data-character"))
}
});
printKeys();
<div class="text">
<input type="text" class="your-text" id="input" placeholder="Your text here..">
<button class="copy-btn">Copy</button>
</div>
<div class="keyboard" id="keyboard"></div>
So I have this transliteration function which I need to execute if the checkbox is checked. The issue is that, the function continues to run after the checkbox is unchecked as well.
const checkBox = document.querySelector("#checkbox");
const input = document.querySelector("#input");
function transRussian(){
ch = ch.replace(/l/g, "л");
ch = ch.replace(/p/g, "п");
return ch;
}
checkBox.addEventListener('change',()=>{
if(checkBox.checked){
transliterate();
}
else{
console.log("transliteration is turned off")
}
});
input.addEventListener('keyup',()=>{
var ch = input.value;
transRussian(ch);
input.value = ch;
});
<input type="checkbox" id="checkbox">
<input type="text" id="input">
In this solution, if the translation checkbox is clicked, the translateBlock() method is called and the text inside the <textarea> element is changed according to the logic.
/* A let variable is declared, not a const, to change the content. */
let checkBox = document.getElementById('checkbox');
let input = document.getElementById('input');
function transRussian(ch){
ch = ch.replace(/l/g, "л");
ch = ch.replace(/p/g, "п");
return ch;
}
function translateBlock(){
var ch = input.value;
input.value = transRussian(ch);
}
/* When the checkbox is clicked, the control variable is set to true. */
input.addEventListener('keyup', () => {
if(checkBox.checked)
translateBlock();
});
/* This method is triggered when data is entered in the <textarea> element. */
checkBox.addEventListener('change', () => {
if(checkBox.checked)
translateBlock();
else
console.log("transliteration is turned off")
});
textarea{
display: block;
}
<span>Translate</span>
<input type="checkbox" id="checkbox"/>
<textarea id="input" name="w3review" rows="4" cols="50">
At w3schools.com you will learn how to make a website. They offer free tutorials in all web development technologies.
</textarea>
I am trying to write a JS function that takes a block of text pasted inside textarea, removes line breaks but keeps paragraph breaks, and updates the text inside that textarea before I submit a form.
I have attempted to do it this way:
<textarea name="sum" id="sum" onpaste="frmt()"></textarea>
JS:
function frmt() {
const tar = document.getElementById("sum");
const reg = /[\r\n](?![\r\n])/g;
const str = tar.value;
tar.innerHTML = str.replace(reg, "");
}
What am I missing?
<textarea name="sum" id="sum"></textarea>
<script>
const sum = document.getElementById('sum');
sum.addEventListener('paste', () =>
setTimeout(
() => (sum.value = sum.value.replace(/[\r\n](?![\r\n])/g, '')),
0
)
);
</script>
https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event
<textarea> is not supported .innerHTML so you need to set values through .value and you can use oninput event.
This event occurs when the value of an <input> or <textarea> element is changed.
Helpful links:
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput
https://www.w3schools.com/jsref/event_oninput.asp
function frmt(id){
const tar = document.getElementById(id);
const reg = /[\r\n](?![\r\n])/g;
const str = tar.value;
tar.value = str.replace(reg, "")
}
textarea{
width: 95%;
height: 160px;
}
<textarea name="sum" id="sum" oninput="frmt('sum')"></textarea>
What I want is filtering user's input. Remove newline and limit its length.
I tried two methods.
https://jsfiddle.net/mj111/356yx1df/3/
html
<div>
<textarea id="text1" placeholder="write down"></textarea>
</div>
<div>
<textarea id="text2" placeholder="write down"></textarea>
</div>
script
document.getElementById('text1')
.addEventListener('input', function (evt) {
evt.preventDefault(); // prevent value change
const msg = evt.target.value.replace(/\n/g, '')
if (msg.length <= 10) {
document.getElementById('text1').value = msg
}
})
document.getElementById('text2')
.addEventListener('input', function (evt) {
const msg = evt.target.value.replace(/\n/g, '').slice(0, 10)
document.getElementById('text2').value = msg
})
First one is not working, because preventDefault is not working. As MDN doc says. 'input' event is not cancelable.
So, I tried second method; just overwrite textarea value.
I think there's a better way to do this. If anyone has a good idea, please answer.
use keyup event to limit length or you can just add maxlength manually to the HTML as an attribute. If you want to set it dynamically you can use Element.setAttribute. For preventing new lines you can prevent the return key, as long as it is not shift. You can still use replace to replace things you feel need replacing, a regular expression will most effectively get the job done.
var text = document.getElementsByTagName('textarea');
var text1 = text[0];
var text2 = text[1];
text1.addEventListener('keydown', function(event) {
let val = event.target.value;
let limit = 25;
// limit the value once you reach a particular length
if (val.length > 3) {
event.target.value = val.substr(0, limit)
};
// prevent new line by preventing enter key press
if (event.keyCode === 13 && !event.shiftKey) {
event.preventDefault();
alert('no new lines please');
return false;
}
// and you can filter with replace
})
<div>
<textarea id="text1" placeholder="write down"></textarea>
</div>
<div>
<textarea id="text2" placeholder="write down"></textarea>
</div>
I would like to replace certain words by **** in my TEXTAREA but this script does not work. Thank you for your help
<TEXTAREA style="color:black;" name="Body" id="Body" value="" rows="6" cols="60" maxlength="160"></TEXTAREA><br/>
<script>
var input = document.getElementById('Body')[0],
output = document.getElementById('Body')[0],
badwords = /\b(test|test2|test3)\b/g;
input.onkeyup = function () {
output.innerHTML = this.value.replace(badwords, function (fullmatch, badword) {
return '<sub>' + new Array(badword.length + 1).join('*') + '</sub>';
});
};
input.onkeyup();
input.focus();
</script>
Here's a working solution, with explanations in the comments:
//remove [0]. getElementById returns an element, not a collection:
var input = document.getElementById('Body'),
output = document.getElementById('Body'),
badwords = /\b(test1|test2|test3)\b/g;
//addEventListener is the best way to add listeners:
input.addEventListener('keyup', function() {
//Change innerHTML to value here:
output.value = this.value.replace(badwords, function (fullmatch, badword) {
//Remove '<sub>...</sub>'. Textareas support text content only.
return new Array(badword.length + 1).join('*');
});
});
input.focus();
<TEXTAREA style="color:black;" name="Body" id="Body" value="" rows="6" cols="60" maxlength="160"></TEXTAREA><br/>