"Utilizing JavaScript, you can remove an element by clicking on the outer element within the

I need the functionality where, when a user clicks on an input type="checkbox", a corresponding textarea is displayed. Then, if the user clicks anywhere except for that specific textarea, it should be hidden. Can someone assist me with implementing this feature? Any suggestions or solutions would be greatly appreciated. Thank you in advance for your help.

var requiredDescription = document.querySelectorAll(".required-description");      
requiredDescription.forEach(item => {
    item.addEventListener('click', function(){            
        item.classList.toggle('active');            
    });        

});
window.addEventListener("click", function(event){
          var desText = document.querySelector('input.active');
          if (event.target !== desText) {
              description.classList.remove('show');                            
          }
      });
.items{
    border: 1px solid var(--txt);
    padding: .5rem;
    border-radius: 10px;
}

p > span.label{
    width: 30%;
    display: block;
}

p > span.label-items{
    width: 70%;
    display: flex; 
    align-items: center; 
    justify-content: space-between;
}

p > span.label-items > lable.label-item{
    display: flex; 
    align-items: center; 
    width: 100%;
}

.description{
    border: 2px solid var(--c2);
    background-color: #e6eef7;
    border-radius: 10px;
    outline: none;
    position: absolute;
    left: 20%;
    top: 10%;
    width: 50%;
    z-index: 1;
    padding: 1rem;
    display: none;
}

p > span.label-items > label.label-item > input.active ~ .description{
    display: block;
}
<p class="items">
   <span class="label">example1</span>
   <span class="label-items">
      <label class="label-item" for="Others">
        <input type="checkbox" name="Others" id="Others" class="required-description">
         Others
        <textarea class="description" placeholder="Define who" cols="50" rows="3"></textarea>                                            
     </label>
   </span>                                    
</p>

<p class="items">
   <span class="label">example2</span>
   <span class="label-items">
       <label class="label-item" for="Yes">
          <input type="checkbox" name="Yes" id="Yes" class="required-description">
          Yes
          <textarea class="description" placeholder="Explain more" cols="50" rows="3"></textarea>
       </label> 
   </span>
</p>

<p class="items">
    <span class="label">example3</span>
    <span class="label-items">
      <label class="label-item" for="ok">
         <input type="checkbox" name="ok" id="ok" class="required-description">
         Yes
          <textarea class="description" placeholder="Define" cols="50" rows="3"></textarea>
     </label> 
    </span>
                                    
                                    
</p>

Answer №1

To implement a click event on the body element and remove a class based on the clicked element, you can use the following approach:

Firstly, select all elements with the class "required-description" and add a click event listener to toggle the 'active' class when clicked.

var requiredDescription = document.querySelectorAll(".required-description");      
requiredDescription.forEach(item => {
    item.addEventListener('click', function(){            
        item.classList.toggle('active');            
    });        
});
document.querySelector('body').addEventListener('click', function(e){
   if(!(e.target.nodeName == 'SPAN' || e.target.nodeName == 'INPUT' || e.target.nodeName == 'TEXTAREA')){ 
requiredDescription.forEach(item => {
       item.classList.remove('active');
       document.querySelectorAll(":checked").forEach(function(chk){
        chk.checked = false;
       });
    });
  }
});

The CSS styles provided define the look of the items and their corresponding labels. The logic ensures that when a checkbox is clicked, its associated textarea is displayed, and clicking anywhere else hides the textarea.

If you encounter any issues or have suggestions for improvement, please feel free to share. Thank you for your cooperation in advance!

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

JavaScript library called "Error: JSON input ended unexpectedly"

I am currently operating a server using node.js and Express v4.0 Additionally, I am utilizing the request library. However, when receiving a response from the server, I encounter an Uncaught SyntaxError: Unexpected end of JSON input. The response I receiv ...

Employing VUE.js for content retrieval

Is there an issue rendering 2 messages in vue.js on the front end? <template v-for="item in items"> <span>{{ afterpayMessage }}: {{ item.price }} with AfterPay</span> </template> <script> var afterpay = new Vue({ e ...

I require adding a new line of information into the database table

I am looking for help with adding data into a table without any user inputs. Specifically, I want to add data by passing them into an array and then be able to call them at the "Add Site" button so that the row is added into the table. Can someone assist m ...

What is the best way to achieve this layout using HTML?

[Beginner in Web Design] I am currently experimenting with creating a layout similar to the one shown here: https://i.sstatic.net/j70FD.png Here is what I have attempted so far: .inner, .outer { position: relative; } .dash { border: 0; borde ...

Tips on maximizing the efficiency of ajax requests to MySQL databases

I have developed a website that needs to fetch data from a database every 2 seconds in order to display a dynamic market with changing prices and volumes. Below is the code I am using: $.ajax({ type: "get", url: "getData.php", data: { ...

css: text not enclosed by a span tag

I created an HTML-CSS demo with two simple span tags. I added some content to each span, and applied the same CSS code to both. Surprisingly, the content of the right span goes beyond the border, while the content of the left span stays within the border. ...

In PHP, ensure to properly close HTML tags within a for each loop

I am currently working with an array called $links. My goal is to generate five links and one HTML container, but I am unsure how to properly close the tags. $i = 0; foreach($links as $link) { if($i==0||!is_float($i / 5)) { echo " ...

Increasing a PHP variable after executing a JavaScript function

Imagine a scenario where we have a database containing numerous items, each with an unsigned integer id (1, 2, ...). Picture a webpage that displays all these items and allows users to add new items temporarily using JavaScript only, without affecting the ...

Taking control of Bootstrap with Kajiki customization

I need to replace this particular table with a Bootstrap table (striped-table). Even though I attempted to directly modify the tags, it didn't yield the desired results. What should be the correct approach for achieving this change? ...

Is there a way to send a variable to PHP and execute it on the current page?

I need to integrate an inventory search feature on a local clothing store's website. The challenge lies in setting up the PHP script that pulls and organizes the data to run on the same page as the search form itself. Given my limited experience with ...

What is the best way to extract the value from a JSON URL?

Using AngularJS, I am looking to dynamically retrieve the price value from a URL's JSON data. Is this feasible? Here is the URL JSON: link Below is my controller: angular.module("myApp",['zingchart-angularjs']).controller('MainContro ...

CSS and the best practices for button styling in a navigation bar

My friend and I are facing a CSS issue while working on a webpage together. We both have limited experience with HTML and CSS. Here's the code snippet in question: .nav li { margin: auto; display: inline-block; color: white; padding: 10px; font ...

What is the best way to address cookie issues while working on a full stack application that utilizes Vue and Express.js?

Developing a full stack application requires me to use Vue on port 5173 and Express on port 3000. One issue I face is the inability to store credentials in the frontend for backend communication during development. This challenge can be addressed by servin ...

What is the best way for me to send a confirmation response to my API once a user has clicked on the activation link

I have been attempting to send a confirmation message to my API after clicking on the activation link, but despite numerous attempts, I have not been successful. Please see the activation link below: <script type="text/javascript> ...

Guide to creating a scrollable container that occupies the remaining height of the screen

Looking to create a fixed container that is scrollable, while keeping the rest of the page fixed? Check out this Stackblitz example. Here's a component called "PageDefault" that includes a Header and wraps each page in the application (the content of ...

Ways to pass JavaScript variables to a Python script

Hey there! I'm currently facing an issue with retrieving variables from JS to use in my python code. Despite trying methods like AJAX and JQuery, I haven't had much success yet. It's possible that I'm missing something crucial in the pr ...

"AngularJS directive mandating the use of the required attribute for internal control

I've encountered a challenge with this specific issue. We are using a directive called deeplink, which contains the following code: restrict: 'E', require: 'ngModel', scope: { smDropdown: '=smDeeplinkDropdown', s ...

Switching iframe content based on screen size

I'm attempting to use jQuery to dynamically change the source, width, and height of an iframe based on the viewport width. Here is the code I currently have: <head> <script type="text/javascript"> $(document).ready(function() ...

What mistakes am I making in including/injecting functions in AngularJS controllers and factories?

I'm encountering an issue in Angular where I am struggling to inject my factory into my controller. The error message I'm receiving is "Cannot read property 'validar' of undefined". In my project, I have two files - ServiceUtil.js which ...

What is causing this get method to return such a message?

One of my functions tabulates user-specific data using a GET method that sends a query parameter userId: <script> let thisArray = [] let = userId = $('#userId').val(); $.ajax({ method:&ap ...