bboooooyintheuk
bboooooyintheuk

Reputation: 143

textbox not hiding with checkbox click (javascript)

I have a textbox which I would like to appear on a checkbox click and disappear if the checkbox is unselected, however my code currently shows the textbox when the page loads, but once you select and then unselect the checkbox it disappears as its supposed to. Any ideas?

Javascript:

function TMDFunction() {
  // Get the checkbox
  var checkBox = document.getElementById("tmd_checkbox");
  // Get the output text
  var text = document.getElementById("test");

  // If the checkbox is checked, display the output text
  if (checkBox.checked == true) {
    text.style.display = 'block';
  } else {
    text.style.display = 'none';
  }
}
<input type="checkbox" class="product" name="targetedmobiledisplay" value="0.08" id="tmd_checkbox" onclick="TMDFunction()">
Targeted Mobile Display
<br> 
Test: <input id="test" type="text" value="0.00" data-total="0" />

Upvotes: 1

Views: 385

Answers (2)

Prince Hernandez
Prince Hernandez

Reputation: 3721

yeah, easy, add the style that you want as default, for example, you want to be display: none, so it is inserted on the HTML.

function TMDFunction() {
  // Get the checkbox
  var checkBox = document.getElementById("tmd_checkbox");
  // Get the output text
  var text = document.getElementById("test");

  // If the checkbox is checked, display the output text
  if (checkBox.checked == true) {
    text.style.display = 'block';
  } else {
    text.style.display = 'none';
  }
}
<input type="checkbox" class="product" name="targetedmobiledisplay" value="0.08" id="tmd_checkbox" onclick="TMDFunction()"> Targeted Mobile Display
<br> 
Test: 
<input id="test" type="text" value="0.00" data-total="0" style="display:none;" />

Upvotes: 1

Sajeth Jonathan
Sajeth Jonathan

Reputation: 48

TMDFunction() only runs when the checkbox is clicked. Initially when the page loads, the function is not being called.

You can try hiding the textbox when the page loads with document.ready.

$( document ).ready(function() {
   var text = document.getElementById("test");
  test.style.display = 'none';
});

This function will hide the textbox once the page loads.

Upvotes: 0

Related Questions