Kiev
Kiev

Reputation: 11

Remove Empty <div> using JavaScript

I am completely new to JavaScript but have managed to cobble together a basic form that returns results based on the checkboxes selected, the issue I'm having is that when only some boxes are ticked I get blank space from the empty divs of the of the unselected checkboxes.

I'd really appreciate any suggestion of how I can remove the empty divs onclick.

The code I am using is below but you can also see a rough example on Codepen.

The rookie JavaScript and HTML:

function checkbox() {
  var finance = document.getElementById("finance").checked;;
  var HR = document.getElementById("HR").checked;
  var Procurement = document.getElementById("Procurement").checked;


  if (finance) document.getElementById("res1").innerHTML = "Some info";
  if (HR) document.getElementById("res2").innerHTML = "Some info";
  if (Procurement) document.getElementById("res3").innerHTML = "Some info";

  return false;
}
<form>
  <input type="checkbox" id="finance" name="Manager" value="Finance"><label for="finance">Finance</label>
  <input type="checkbox" id="HR" name="Manager" value="HR"><label for="HR">HR</label>
  <input type="checkbox" id="Procurement" name="Manager" value="Procurement"><label for="Procurement">Procurement</label>
  <input type="submit" value="See Training" size="30" onClick="return checkbox();">
  <input type="submit" value="Reset" size="30" onClick="return reset();">
</form>

<div id="res1"></div>
<div id="res2"></div>
<div id="res3"></div>

Upvotes: 0

Views: 3788

Answers (4)

Scott Marcus
Scott Marcus

Reputation: 65796

There is a better approach here that is more dynamic and should resolve the issue of getting space when no content is in the div. This way, you don't have to test for any particular checkbox and match it to a particular div.

Also, you were using a submit button type for your reset button, which isn't right and you should not use inline HTML event attributes (onsubmit, onclick, etc.) there are a number of reasons why. Instead, use the modern, standards-based approach and keep your HTML clean.

See additional comments inline below:

// Get all the checkboxes and div elements into respective arrays:
var chks = Array.from(document.querySelectorAll("input[type=checkbox]"));
var divs = Array.from(document.querySelectorAll("div.output"));

// Get reference to Reset button
var reset = document.querySelector("input[type=reset]");

// Loop over all the checkboxes...
chks.forEach(function(box){

  // Assign each one a click event handler:
  box.addEventListener("click", function checkbox(evt) {
    // Get the index of the position of the checkbox in the checkbox array
    var idx = chks.indexOf(box);
  
    if(box.checked){
     // Populate the corresponding div in its array and unhide it:
     divs[idx].textContent = box.value;
     divs[idx].classList.remove("hidden");
    } else {
     // The box is unchecked, so re-hide it
     divs[idx].classList.add("hidden");  
    }
  });

});

reset.addEventListener("click", function(){
  // Loop over the divs and hide each of them:
  divs.forEach(function(div){
   div.classList.add("hidden"); 
  });
});
/* All the divs related to checkboxes are hidden by default */
.hidden { display:none; }
<form>
  <input type="checkbox" id="finance" name="Manager" value="Finance"><label for="finance">Finance</label>
  <input type="checkbox" id="HR" name="Manager" value="HR"><label for="HR">HR</label>
  <input type="checkbox" id="Procurement" name="Manager" value="Procurement"><label for="Procurement">Procurement</label>
  <input type="submit" value="See Training" size="30">
  <input type="reset" value="Reset" size="30">
</form>

<div id="res1" class="output hidden"></div>
<div id="res2" class="output hidden"></div>
<div id="res3" class="output hidden"></div>

Upvotes: 0

Lewis Campbell
Lewis Campbell

Reputation: 353

So there are a few different ways you can achieve this. Within your javascript where you add the content to the divs you can add else statements to hide/delete the redundant divs, or after you've added all the required content you could loop through your divs and hide/delete any that don't have content.

I would recommend against deleting the divs, as that would mean you have to add them each time you reset your from. Instead, you can add the style display: none This will remove them from the DOM, and thus remove the whitespace.

Another piece of advice - Don't use <br /> tags after your divs. Divs by default are blocks, and will force a new line after. If you need more space, it would be better to add bottom margin.

Below is an edited version of your codepen that hides any of the divs that are not required.

function checkbox() {
  var finance = document.getElementById("finance").checked;
  var HR = document.getElementById("HR").checked;
  var Procurement = document.getElementById("Procurement").checked;
  var Appraisal = document.getElementById("Appraisal").checked;
  var HS = document.getElementById("HS").checked;
  var MSS = document.getElementById("MSS").checked;

  if (finance){
    document.getElementById("res1").innerHTML =
      "<strong>Finance</strong><br/>Finance Results";
  }else{
    document.getElementById("res1").classList.add("hide");
  }
  if (HR){
    document.getElementById("res2").innerHTML = "<b>HR</b><br/>HR Results";
  }else{
    document.getElementById("res2").classList.add("hide");
  }
  if (Procurement){
    document.getElementById("res3").innerHTML =
      "<b>Procurement</b><br/>Procurement Results";
  }else{
    document.getElementById("res3").classList.add("hide");
  }
  if (Appraisal){
    document.getElementById("res4").innerHTML =
      "<b>Appraisal</b><br/>Appraisal Results";
  }else{
    document.getElementById("res4").classList.add("hide");
  }
  if (HS) {
    document.getElementById("res5").innerHTML =
      "<b>Health & Safety</b><br/>Health & Safety Results";
  } else {
    document.getElementById("res5").classList.add("hide");
  }
  if (MSS) {
    document.getElementById("res6").innerHTML = "<b>MSS</b><br/>MSS Results";
  } else {
    document.getElementById("res6").classList.add("hide");
  }

  return false;
}
input[type="checkbox"] + label {
  position: absolute;
  width: 30px;
  height: 30px;
  border: 5px solid #555;
  border-radius: 50%;
  left: 50px;
  -webkit-transform: translate(-50%, -50%);
          transform: translate(-50%, -50%);
  -webkit-transition: all ease-out 200ms;
  transition: all ease-out 200ms;
  text-indent: 45px;
  font: normal normal 25px/40px "Helvetica";
  white-space: nowrap;
  color: #555;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}

input[type="checkbox"] + label:after {
  content: "";
  position: absolute;
  width: 0px;
  height: 13px;
  border-bottom: 5px solid #22b573;
  border-left: 5px solid #22b573;
  top: 25%;
  left: 50%;
  -webkit-transform-origin: bottom left;
          transform-origin: bottom left;
  -webkit-transform: rotate(-45deg);
          transform: rotate(-45deg);
  opacity: 0;
  -webkit-transition: all ease-out 200ms;
  transition: all ease-out 200ms;
}

input[type="checkbox"]:checked + label {
  border: 5px solid #22b573;
}

input[type="checkbox"]:checked + label:after {
  opacity: 1;
  width: 35px;
}

#finance {
  display: none;
}

#HR {
  display: none;
}

#Procurement {
  display: none;
}

#Appraisal {
  display: none;
}

#HS {
  display: none;
}

#MSS {
  display: none;
}

.hide{
  display: none;
}
<p>I need information about:</p><br/>
<form>
    <input type="checkbox" id="finance" name="Manager" value="Finance"><label for="finance">Finance</label><br/><br/><br/>
    <input type="checkbox" id="HR" name="Manager" value="HR"><label for="HR">HR</label><br/><br/><br/>
    <input type="checkbox" id="Procurement" name="Manager" value="Procurement"><label for="Procurement">Procurement</label><br/><br/><br/>
    <input type="checkbox" id="Appraisal" name="Manager" value="Appraisal"><label for="Appraisal">Appraisal</label><br/><br/><br/>
    <input type="checkbox" id="HS" name="Manager" value="Hs"/><label for="HS">Health & Safety</label><br/><br/><br/>
    <input type="checkbox" id="MSS" name="Manager" value="MSS"><label for="MSS">MSS</label><br/><br/><br/>
    <input type="submit" value="See Training" size="30" onClick="return checkbox();">
    <input type="submit" value="Reset" size="30" onClick="return reset();">
</form><br/>
<div id="mandatory"><b>Mandatory</b><br/>The mandatory training all managers have to do</div><br/>
<div id="res1"></div>
<div id="res2"></div>
<div id="res3"></div>
<div id="res4"></div>
<div id="res5"></div>
<div id="res6"></div>

Upvotes: 1

JLRishe
JLRishe

Reputation: 101700

The extra <div>s aren't taking up space. The <br>s after them are adding extra line breaks.

Just remove the <br>s from the original HTML and place them inside the divs that you do populate (when you populate them).

Upvotes: 1

Baruch
Baruch

Reputation: 2428

There's a few steps

  1. You need to get all the divs
  2. Loop through the divs and find the empty ones
  3. Use remove() to, well, remove the node.

Fiddle: https://jsfiddle.net/3snod1ry/

const divs = document.querySelector('div');

divs.forEach(div => {
  if (divs.innerHTML === '') {
    div.remove();
  }
});

Upvotes: 1

Related Questions