I have a Javascript code with if and alse. Practically, I have two div that will show after selected checkbox (one and/or both) and click on link.
I’d like that for the first time divs shall go in show when click on link, starting from after first click I’d like show div only if user click on checkboxes.
I use myvariable to made this check, but seems that doesn’t work.. Following the code:
<label for="myCheck1">Checkbox1:</label>
<input type="checkbox" id="chk1" onclick="showDiv2()">
<label for="myCheck2">Checkbox2:</label>
<input type="checkbox" id="chk2" onclick="showDiv2()"><br>
<a id="link-id" href="javascript: void(0)">Next</a>
<div id="text1" class="div1">Div no 1</div>
<div id="text2" class="div2">Div no 2</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$div1 = $(".div1");
$div2 = $(".div2");
$div1.hide()
$div2.hide()
let myvariable = false;
if (myvariable == false) {
function showDiv1() {
myvariable = true;
if (document.getElementById('chk1').checked) {
$div1.show()
} else {
$div1.hide()
}
if (document.getElementById('chk2').checked) {
$div2.show()
} else {
$div2.hide()
}
}
$('#link-id').on('click', showDiv1)
} else {
function showDiv2() {
var checkBox1 = document.getElementById("chk1");
var text1 = document.getElementById("text1");
var checkBox2 = document.getElementById("chk2");
var text2 = document.getElementById("text2");
if (checkBox1.checked == true) {
text1.style.display = "block";
} else {
text1.style.display = "none";
}
if (checkBox2.checked == true) {
text2.style.display = "block";
} else {
text2.style.display = "none";
}
}
}
2
Answers
No need to use if and variables like this
Rewritten your code to make it work