Ways to display the innerHTML of a textarea once the current content has been removed

My current task involves toggling the visibility of a textarea's innerHTML based on focus and blur events. The functionality is working as expected, but I have encountered an issue. When I delete the text entered in the textarea, the innerHTML remains hidden even though it still exists within the element. Here are the steps to replicate the issue:

  1. Enter text inside the textarea
  2. Select all the text and delete it
  3. Mouse out from the textarea
  4. The innerHTML is not visible in the browser
  5. However, the innerHTML is visible when inspecting elements in the browser
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>

Answer №1

To update or retrieve the value of a textarea, it is recommended to use the .value property instead of .innerHTML. The innerHTML property does not reflect changes made to the textarea's content in the browser.

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>

Answer №2

This code snippet showcases how to manipulate placeholder text in a textarea element:

<textarea name="" id="" cols="30" rows="10" placeholder='Test'></textarea>
let allTextareas = document.querySelectorAll("textarea");

for(let i=0; i<allTextareas.length; i++) {
  let currentPlaceholder = allTextareas[i].placeholder;
  
  allTextareas[i].addEventListener("focus", (e) => {
    console.log(e.target.placeholder);
    e.target.placeholder = '';
  });

  allTextareas[i].addEventListener("blur", (e) => {
    e.target.placeholder = currentPlaceholder;
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing JavaScript: Grouping JSON Response by Date and Category in a Table

The API response provided below contains sample data. {"success":true,"transaction":[{"_id":"58efd5717ddda769f26793fc","transId":"Exp/04-17/17","trpId":"Trav/dfsd/04-17/12","tripId":"58efd4dc7ddda769f26793f8","userId":"58ac19eaec1e7e4628be6f01","expenseHe ...

align image vertically within a floated container

There are 5 floated divs with heights stretched to 100% of the document height using JavaScript. Each of the 5 divs contains an img element. <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <lin ...

"Enhance your data management with Laravel and Vue.js by incorporating the powerful Matfish Vue-Table

Currently, I am utilizing matfish-vue-table2 along with server-side implementation. Below is my Laravel controller where I am able to retrieve the JSON response from the 'api/articles' URL: public function index() { $articles = Article::orde ...

How to use jQuery to scroll to the top of a specific container div

The accordion menu I am currently using was created by Ian Flynn of RocketMill and can be found here: Although this accordion has served me well in the past, I have encountered a new challenge with a client who prefers to have more content. This causes is ...

Implementing AngularJS ng-show and ng-hide directives with animated toggle class

Looking for guidance on how to make use of ng-hide and ng-show animations for toggling classes. I want a default div that is hidden initially. When I click the button, it should slide in from left to right with animation. Clicking the same button again sh ...

Tips on aligning a span element at the center of an image without losing its mouseover

<div class="pic"> <img src="image.jpg" height="250"/> <span class="text" style="display:none">text here</span> </div> <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </scrip ...

On my WordPress Elementor website, I am looking to have the button on my product card linked to a specific

I found a product card design on codepen.io and tried to customize it by changing the colors. However, I'm struggling to get the button to work. Here is the product card code snippet: <div class="card"> <div class="imgBox&q ...

Guide to clicking on a Javascript button using Selenium

On the webpage, there are multiple rows with buttons having the same name. I am facing issues with XPath as the ID is identical for all the rows, which is //*[@id="btnChangeStatusThisOrder"] Below is the code for one specific row that contains the button ...

What is the best way to extend the width of an element within a Bootstrap column beyond the column itself?

Apologies for any language errors, but I have a query regarding Bootstrap. I am currently working on making a website responsive and I have a row with 4 columns set up like this: The "seeMore" div is initially hidden and on clicking the boxToggle element ...

Exploring the world of Bootstrap Twitter 3.0 alongside the wonders of Knockout

When utilizing Twitter Bootstrap, the validation classes like has-error or has-warning must be added to the wrapping form-group element to style both the input and its label. However, Knockout-Validation directly adds the class to the input element itself. ...

Is it true that Firefox fails to display javascript errors on AJAX 'threads'?

Currently, I have a function called test_fn that is being called in two ways: (a) Through an onclick event of a button; or (b) from the success callback within a jQuery AJAX request, as shown here: $.ajax({ type: 'POST', ... succes ...

Using React's state to hide a div reveals the div with a flicker when saving the information

Is there a way to create a hidden div that the user can show with a button in React Next.js without it flashing on reload? const [showBanner, setShowBanner] = useState(true); useEffect(() => { const data = window.localStorage.getItem('STATE& ...

What are the steps for initializing a session in Vue.js with Django upon a successful login?

Upon successful login, I want to redirect to a page indicating success and also include a session. How can this be achieved? I am using HTML with Vue.js for the front end and Django for the back end. Below is my Vue.js script for the login: <script> ...

Challenge: RxJS timeout function not functioning as expected

I am facing an issue with exiting the Observable stream after 3 seconds if there is no new string input. The problem arises when I paste the same value multiple times, as the distinctUntilChanged operator prevents the input stream from progressing. I wan ...

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

Hide dropdown when clicked outside of it

Can someone help me modify my JavaScript code so that when I click on a new dropdown, it closes the previous one and keeps only the current one open? function manageDropdowns() { var dropdowns = document.querySelectorAll('.dropdown:not(.is-hove ...

The value returned by a component should remain consistent regardless of where it is invoked. Additionally, the main component in React should not re-render when the state of a sub-component is

I am looking to have the same value displayed in the Home function from the Component, without causing a rerender when the useState in Component is updated. import { useState, useEffect } from "react"; function Component() { const [count, setC ...

Sorting objects in an array according to their prices: A guide

Suppose we have the following data structure: var lowestPricesCars = { HondaC: { owner: "", price: 45156 }, FordNew: { owner: "", price:4100 }, HondaOld: { owner: "", price: 45745 }, FordOld: { owner: "", ...

Troubleshooting issue with jQuery subtraction not functioning as expected

Everything seems to be functioning correctly except for the subtraction operation. function add_culture(ele) { total=parseInt($('#total_price').val()); culture_price=parseInt($('#culture_price').val()); $(& ...

``As I navigate through my react native app, I encounter the challenge of receiving the BackHandler

I've been developing a chat app and I'm trying to implement a feature where, upon clicking the default back button on Android, it both closes the keyboard and navigates back. Although I know how to capture the keyboard close event, I currently h ...