How to make show function in if if, otherwise override hide function forever?

in this code, I want the show function (right or wrong answer) to continue, but it always comes back to hide

$("#correctOne").hide();
$("#incorrectOne").hide();

function myFunction() {
  var inputOne = $("#inputOne").val();
  if (inputOne == 10) {
    $("#correctOne").show();
    //confirm("Correct");
  } else {
    $("#incorrectOne").show();
    //confirm("Incorrect");
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>What number am I thinking of?</h1>
<p>Divide me by four and my remainder is two. I am net if you see me through the looking glass.</p>
<form>
  <input id="inputOne" type="text" placeholder="Answer Here">

  <button onclick="myFunction()">submit</button>
</form>
<h2 id="correctOne">Yes!</h2>
<h3 id="incorrectOne">Nope!</h3>
Run codeHide result
+4
source share
2 answers

You need to first hide both of them inside the function body.

  
$("#correctOne").hide();
$("#incorrectOne").hide();

function myFunction() {
$("#correctOne").hide();
$("#incorrectOne").hide();
var inputOne = $("#inputOne").val();
if (inputOne == 10) {
$("#correctOne").show();
//confirm("Correct");
} else {
$("#incorrectOne").show();
//confirm("Incorrect");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>What number am I thinking of?</h1>
<p>Divide me by four and my remainder is two. I am net if you see me through the looking glass. </p>
<form>
<input id="inputOne" type="text" placeholder="Answer Here">

<button onclick="myFunction()">submit</button>
</form>
<h2 id = "correctOne">Yes!</h2>
<h3 id = "incorrectOne">Nope!</h3>
Run codeHide result
0
source

Add button type in button layout:

<button type="button" onclick="myFunction()">submit</button>

Why?

Since the functionality of the button by default is to submit the form, and your form will be submitted when you click the button and due to the postback , your elements will be hidden as the document is ready again.

  • press the button.
  • .
  • .
  • postback, .
  • .

.toggle(boolean):

$("#correctOne").hide();
$("#incorrectOne").hide();

function myFunction() {
  var inputOne = $("#inputOne").val();

  $("#correctOne").toggle(inputOne == 10); // .toggle(true) to show
  $("#incorrectOne").toggle(inputOne != 10); // .toggle(false) to hide

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>What number am I thinking of?</h1>
<p>Divide me by four and my remainder is two. I am net if you see me through the looking glass.</p>
<form>
  <input id="inputOne" type="text" placeholder="Answer Here">

  <button type="button" onclick="myFunction()">submit</button>
</form>
<h2 id="correctOne">Yes!</h2>
<h3 id="incorrectOne">Nope!</h3>
Hide result
+1

Source: https://habr.com/ru/post/1666072/


All Articles