0

I have a page with such structure

    <div id=0>
    ...
       <textarea id=sometext></textarea>
       ...
          <button class="coolbutton"></button>
       ...
    ...
    </div>
    <div id=1>
    ...
       <textarea id=sometext></textarea>
       ...
          <button class="coolbutton"></button>
       ...
    ...
    </div>
    <div id=2>
    ...
       <textarea id=sometext></textarea>
       ...
          <button class="coolbutton"></button>
       ...
    ...
    </div>

I need to hide button only in the first div (id=0) when textarea in this div is empty. Please notice that only div ids differs. Ids of textareas are same. Buttons in other divs don't need to be hidden.
Please provide solution using js or asp.net mvc tools. Ask me if anything is unclear.

Storm
  • 557
  • 1
  • 8
  • 25
  • 3
    1. All your `textareas` have the same `id`, this is wrong. `ids` are unique. 2. Add a `className` or `style` to your first `button` that hides it. Then add an `event listener` to your first `textarea` so that when the `value` changes it can unhide/re hide the button. – Ryan Wilson Nov 10 '20 at 15:19
  • @RyanWilson these divs are created using a cycle so I can't add event to only the first textarea. Therefore I guess I can create event listeners on all textareas and pass div id there somehow so I can check it in a function to hide only the first button. But still not the best solution I guess... – Storm Nov 10 '20 at 15:25
  • 2
    'these divs are created using a cycle so I can't add event to only the first textarea' sure you can: `.commonDivClass:first`, or in plain CSS: https://stackoverflow.com/a/8539107/519413 – Rory McCrossan Nov 10 '20 at 15:26

1 Answers1

0

See my solution below. Since all of your buttons have the same id you can use childNodes to target the empty text area in the first div.

If the first textarea in div1 is empty then hide its second child which is the button.

The code snippet has comments for explanation.

//Declare div one using childNodes
  var div1 = document.getElementById("0").childNodes;
  
  //Target second child of div using index [1]
  //The second child of the first div is the empty text area
  if (div1[1].innerHTML === "") {
  //If the text area is empty then hide the button
  div1[3].style.display = "none";
  }
<div id="0">
       <textarea id="sometext"></textarea>
          <button class="coolbutton">Click</button>
    </div>
    <div id="1">
       <textarea id="sometext">some text</textarea>
          <button class="coolbutton">Click</button>
    </div>
    <div id="2">
       <textarea id="sometext">some text</textarea>
          <button class="coolbutton">Click</button>
    </div>
Aib Syed
  • 3,118
  • 2
  • 19
  • 30