Home > Blockchain >  How to auto checked the checkbox and auto display the results when checked
How to auto checked the checkbox and auto display the results when checked

Time:09-12

This is my code for checkbox, I want to make this auto checked and display also the results when checked

<!DOCTYPE html>
<html>
<body>

<p>Display some text when the checkbox is checked:</p>

<label for="myCheck">Checkbox:</label> 
<input type="checkbox" id="myCheck" onclick="myFunction()">

<p id="text" style="display:none">Checkbox is CHECKED!</p>

<script>
function myFunction() {
  var checkBox = document.getElementById("myCheck");
  var text = document.getElementById("text");
  if (checkBox.checked == true){
    text.style.display = "block";
  } else {
     text.style.display = "none";
  }
}
</script>

</body>
</html>

CodePudding user response:

You can add a function when the content is loaded,then set checkbox to be checked,finally invoke myFunction method

<!DOCTYPE html>
<html>
<body onl oad="init()">

<p>Display some text when the checkbox is checked:</p>

<label for="myCheck">Checkbox:</label> 
<input type="checkbox" id="myCheck" onclick="myFunction()">

<p id="text" style="display:none">Checkbox is CHECKED!</p>

<script>
function init(){
     var checkBox = document.getElementById("myCheck");
     checkBox.checked = true;
     myFunction();
}

function myFunction() {
  var checkBox = document.getElementById("myCheck");
  var text = document.getElementById("text");
  if (checkBox.checked == true){
    text.style.display = "block";
  } else {
     text.style.display = "none";
  }
}
</script>

</body>
</html>

CodePudding user response:

$('#myCheck').prop('checked',true);
myFunction();
function myFunction() 
{
  if($('#myCheck').prop("checked") == true)
  {
      $('#text').show();
  }
  else
  {
    $('#text').hide();
  }
}
<!DOCTYPE html>
<html>

<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Display some text when the checkbox is checked:</p>

<label for="myCheck">Checkbox:</label> 
<input type="checkbox" id="myCheck" onclick="myFunction()">

<p id="text">Checkbox is CHECKED!</p>

</body>
</html>

  • Related