1

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" />

2
  • 1
    just add simple CSS to the textbox to set it to display none... #test{display:none} OR call TMDFunction() onload of your page Commented Jan 30, 2020 at 16:56
  • 1
    Side note; text.style.display = (checkBox.checked ? 'block' : 'none'); Commented Jan 30, 2020 at 16:59

2 Answers 2

1

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;" />

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

how would I hide the text beside it? Should I add to a label and place inside the function?
Wrap the text and the textbox inside a <div> and hide it when the page loads

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.