Checkbox onchange show div and cheked another checkbox - javascript

How can I modify this code. Can I use one evenlistner there to implement the same result. What is the best practice in this case. Can I use here data atribute, or querySelector better. codepen
const myCheck = document.getElementById("check");
const myCheck2 = document.getElementById("check2");
const dib = document.getElementById("dib");
function change() {
if (myCheck2.checked) {
myCheck.checked = false;
dib.style.display = "block";
}
else{
dib.style.display = "none";
myCheck.checked = true;
}
}
function func2() {
if (this.checked) {
myCheck2.checked = false;
dib.style.display = "none";
}
else {
dib.style.display = "block";
myCheck2.checked = true;
}
}
myCheck2.addEventListener('click', change);
myCheck.addEventListener('click', func2);
<input type="checkbox" id="check" >
<input type="checkbox" id="check2" checked="checked" >
<div id="dib">Text</div>

Two improvements you could make to your existing code without changing the logic at all would be to use meaningful names for your functions, and to fix the indenting. But anyway...
If I've understood your existing code, the idea is that when either checkbox is checked the other should be automatically unchecked (in which case why not use radio buttons?), and the associated div should be displayed only if the second checkbox is checked? If so, you could combine the code into a single function as follows:
const myCheck = document.getElementById("check");
const myCheck2 = document.getElementById("check2");
const dib = document.getElementById("dib");
function cbChanged() {
(this === myCheck ? myCheck2 : myCheck).checked = !this.checked;
dib.style.display = myCheck2.checked ? "block" : "none";
}
myCheck2.addEventListener('click', cbChanged);
myCheck.addEventListener('click', cbChanged);
<input type="checkbox" id="check" >
<input type="checkbox" id="check2" checked="checked">
<div id="dib">Text</div>
Notice that the above still binds two event listeners, but to the same function.
Below is a more generic version that uses a container around the checkboxes and their associated div so that you could have multiple copies of that on the page all handled by one event listener wired up with a similar amount of JS to the previous version:
function cbChanged(e) {
const showCB = this.querySelector(".show");
const hideCB = this.querySelector(".hide");
(e.target === hideCB ? showCB : hideCB).checked = !e.target.checked;
this.querySelector("div").style.display = showCB.checked ? "block" : "none";
}
const containers = document.querySelectorAll(".container");
Array.prototype.forEach.call(containers, function(el) {
el.addEventListener('click', cbChanged);
});
<div class="container">
<input type="checkbox" class="hide" >
<input type="checkbox" class="show" checked="checked">
<div>Text One</div>
</div>
<div class="container">
<input type="checkbox" class="hide" >
<input type="checkbox" class="show" checked="checked">
<div>Text Two</div>
</div>
<div class="container">
<input type="checkbox" class="hide" >
<input type="checkbox" class="show" checked="checked">
<div>Text Three</div>
</div>

Related

If both checkboxes are true, then show DIV

I am trying to show a Div that contains a button element, but only when BOTH checkboxes have been "agreed" to.
I have tried to use JS to check this and then set the style display when each checkbox is clicked.
HTML:
<div class="agreement_box">
<input type="checkbox" id="box1" onclick="showMe('submit_btn')">
</div>
<br>
<div class="agreement_box">
<input type="checkbox" id="box2" onclick="showMe('submit_btn')">
</div>
<div id="submit_btn" class="profileSubmit_btn" style="display:none">
<button>
BUTTON
</button>
</div>
JS:
function showMe(box) {
var chbox1 = document.getElementByID("box1");
var chbox2 = document.getElementByID("box2");
var vis = "none";
if (chbox1.checked && chbox2.checked) {
vis = "block";
break;
}
document.getElementById(box).style.display = vis;
}
Fiddle: https://jsfiddle.net/nhykqodp/2/
I'm kinda new to JS and my HTML knowledge is about 10 years out of date at this point. Any help would be appreciated.
Thanks.
If I run your code, it shows:
Uncaught SyntaxError: Illegal break statement
Thats because a break
can only be used inside a loop.
Furthermore, you have a typo, it should be getElementById instead of getElementByID
Note: The d shouldn't be capitalised
Remove the break
Fix the typos:
function showMe(box) {
var chbox1 = document.getElementById("box1");
var chbox2 = document.getElementById("box2");
var vis = "none";
if (chbox1.checked && chbox2.checked) {
vis = "block";
}
document.getElementById(box).style.display = vis;
}
<div class="agreement_box">
<input type="checkbox" id="box1" onclick="showMe('submit_btn')">
</div>
<br>
<div class="agreement_box">
<input type="checkbox" id="box2" onclick="showMe('submit_btn')">
</div>
<div id="submit_btn" class="profileSubmit_btn" style="display:none">
<button>
BUTTON
</button>
</div>
Using an in-line if statement, we can remove the vis variable so we can alter the style right away like so:
function showMe(box) {
const chbox1 = document.getElementById("box1");
const chbox2 = document.getElementById("box2");
document.getElementById(box).style.display = (chbox1.checked && chbox2.checked) ? 'block' : 'none';
}
function showMe(box) {
const chbox1 = document.getElementById("box1");
const chbox2 = document.getElementById("box2");
document.getElementById(box).style.display = (chbox1.checked && chbox2.checked) ? 'block' : 'none';
}
<div class="agreement_box">
<input type="checkbox" id="box1" onclick="showMe('submit_btn')">
</div>
<br>
<div class="agreement_box">
<input type="checkbox" id="box2" onclick="showMe('submit_btn')">
</div>
<div id="submit_btn" class="profileSubmit_btn" style="display:none">
<button>
BUTTON
</button>
</div>
The syntax errors have already been pointed out; for hiding/showing elements these already have an API which is called el.hidden. I recommend you use it.
Aside from that, you shouldn't use inline event handlers like onclick. Instead, use EventTarget.addEventListener().
I've also generalized your code, so that any number of checkboxes can act as toggle for any element, given that element has the id that you define in data-toggle on the checkboxes.
const checkboxes = Array.from(document.querySelectorAll('[data-toggle]'));
function allChecked(toggle) {
return checkboxes.filter(cb => cb.dataset.toggle === toggle).every(cb => cb.checked);
}
for (const checkbox of checkboxes) {
checkbox.addEventListener('change', function() {
document.getElementById(this.dataset.toggle).hidden = !allChecked(this.dataset.toggle);
});
}
<div class="agreement_box">
<input type="checkbox" data-toggle="submit_btn">
</div>
<br>
<div class="agreement_box">
<input type="checkbox" data-toggle="submit_btn">
</div>
<div id="submit_btn" class="profileSubmit_btn" hidden>
<button>
BUTTON
</button>
</div>
Little syntax error just replace document.getElementByID to document.getElementById

Javascript change inner HTML

I'd like to change the value of a label depending on the status of its checkbox
function private() {
var checkBox = document.getElementById("private");// Get the checkbox
var text = document.querySelector('label[for="private"]');// Get the output text
if (checkBox.checked == true)
{
text.innerHTML = "Public";
} else {
text.innerHTML = "Private";
}
}
<label class="switch">
<input id="private" type="checkbox" onclick="private()" />
<span class="slider"></span>
</label>
<label for="private"></label>
Why doesn't this work?
querySelectorAll returns a nodelist, so you need to specify the element you want like:
function private() {
var checkBox = document.getElementById("private");// Get the checkbox
var text = document.querySelectorAll('label[for="private"]')[0];// Get the output text
if (checkBox.checked == true)
{
text.innerHTML = "Public";
} else {
text.innerHTML = "Private";
}
}
<label class="switch">
<input id="private" type="checkbox" onclick="private()" />
<span class="slider"></span>
</label>
<label for="private"></label>
Or maybe just use querySelector instead which only returns the first match:
function private() {
var checkBox = document.getElementById("private");// Get the checkbox
var text = document.querySelector('label[for="private"]');// Get the output text
if (checkBox.checked == true)
{
text.innerHTML = "Public";
} else {
text.innerHTML = "Private";
}
}
<label class="switch">
<input id="private" type="checkbox" onclick="private()" />
<span class="slider"></span>
</label>
<label for="private"></label>
You need to use querySelector() not querySelectorAll(). By getting all elements, you would have to iterate through the list of items (even though there is only 1).
function private() {
var checkBox = document.getElementById("private");// Get the checkbox
var text = document.querySelector('label[for="private"]');// Get the output text
if (checkBox.checked == true)
{
text.innerHTML = "Public";
} else {
text.innerHTML = "Private";
}
}
<label class="switch">
<input id="private" type="checkbox" onclick="private()" />
<span class="slider"></span>
</label>
<label for="private"></label>
There are three things that I would suggest that will solve your problem:
Pass the event object to your function. This contains everything about the click event, including what element was clicked on. This means you don't have to scour the DOM.
Do not wrap a form control with a label. This is not how labels were intended to work. Instead use something like a section tag.
Form controls and their labels are automatically connected when a for attribute is provided. The other can be found through control.labels[0] or label.htmlFor. This is particularly why you want to adhere to the standard of not wrapping controls with labels
With these adjustments, and the addition of a ternary condition statement to determine what text to display, the code will look like this:
<section class="switch">
<input id="private" type="checkbox" onclick="private(event)" />
<span class="slider"></span>
</section>
<label for="private"></label>
function private(e) {
var checkBox = e.currentTarget,
label = checkBox.labels[0];
label.textContent = checkBox.checked ? "Public" : "Private";
}
Example:
function private(e) {
var checkBox = e.currentTarget,
label = checkBox.labels[0];
label.textContent = checkBox.checked ? "Public" : "Private";
}
<section class="switch">
<input id="private" type="checkbox" onclick="private(event)" />
<span class="slider"></span>
</section>
<label for="private"></label>

Several input checkbox using one JS with different var

I have 3 input checkboxes. Each of them displays a div if checked. Because the three has the same JS I have decided to have just one JS including 3 variables (one per input) but it is not working. Before I had three independent JS and it worked fine.
CODE
document.getElementById()
var cb1 = document.getElementById('checkbox1'); checkbox1.onchange = {
if (checkbox1.checked) {
course1.style.display = 'block';
} else {
course1.style.display = 'none';
};
var cb2 = document.getElementById('checkbox2'); checkbox2.onchange = {
if (checkbox2.checked) {
course2.style.display = 'block';
} else {
course2.style.display = 'none';
};
var cb3 = document.getElementById('checkbox3'); checkbox3.onchange = {
if (checkbox3.checked) {
course3.style.display = 'block';
} else {
course3.style.display = 'none';
};
<form>
<label class="switch">
<input type="checkbox" id="checkbox1"> Course 1
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox2"> Course 2
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox3"> Course 3
</label>
</form>
<br>
<div id ="course1">
Text course 1
</div>
<br>
<div id ="course2">
Text course 2
</div>
<br>
<div id ="course3">
Text course 3
</div>
Fiddle: https://codepen.io/antonioagar1/pen/YOwBeE?editors=1010
After fixing your syntax errors (identation is very imporant, if it was correct in your code you would had see that you have many if statements not closing correclty)
Well, besides those errors, I managed a way to you that you only need a single function to achieve your desired result.
If you see in the HTML part, you'll note that I added some new attributes to checkboxes and divs, called data-idCheck, where the checkbox with data-idCheck will display the div whose have that same attribute.
Check below to see if my code helps you.
var cb1 = document.getElementById('checkbox1');
cb1.onchange = checkChecked;
var cb2 = document.getElementById('checkbox2');
cb2.onchange = checkChecked;
var cb3 = document.getElementById('checkbox3');
cb3.onchange = checkChecked;
function checkChecked(){
let idCheck = this.getAttribute("data-idCheck");
let relatedDiv = document.querySelector("div[data-idCheck='" + idCheck + "']");
if (this.checked) {
relatedDiv.style.display = 'block';
} else {
relatedDiv.style.display = 'none';
}
}
.hiddenDiv{
display: none;
}
<form>
<label class="switch">
<input type="checkbox" id="checkbox1" data-idCheck="1"> Course 1
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox2" data-idCheck="2"> Course 2
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox3" data-idCheck="3"> Course 3
</label>
</form>
<br>
<div id ="course1" class="hiddenDiv" data-idCheck="1">
Text course 1
</div>
<br>
<div id ="course2" class="hiddenDiv" data-idCheck="2">
Text course 2
</div>
<br>
<div id ="course3" class="hiddenDiv" data-idCheck="3">
Text course 3
</div>

Save Radio Box Value in Variables

I want to save the checked values of the radio boxes but when I try to submit the button and redirect to a url based on the 3 choices it doesnt work. I debugged it, and apparently the problem is that my program is only saving the last value in the variable but not the values before. What can I do to save all the choices in 3 different variables?
HTML:
<div id="schritt1">
<p stlye="text-align:center;">frage 1</p>
<input id="1a" type="radio" name="a" value="eins" onclick="checkedvalue('a')"/>
<label for="1a">1</label><br/>
<input id="1b" type="radio" name="a" value="zwei" onclick="checkedvalue('a')"/>
<label for="1b">2</label></br>
<input id="1c" type="radio" name="a" value="drei" onclick="checkedvalue('a')"/>
<label for="1c">3</label>
</div>
<div id="schritt2" style="display:none;">
<p stlye="text-align:center;">Frage 2</p>
<input id="2a" type="radio" name="b" value="zweieins" onclick="checkedvalue('b')"/>
<label for="2a">1</label><br/>
<input id="2b" type="radio" name="b" value="zweizwei" onclick="checkedvalue('b')"/>
<label for="2b">2</label></br>
<input id="2c" type="radio" name="b" value="zweidrei" onclick="checkedvalue('b')"/>
<label for="2c">3</label>
</div>
<div id="schritt3" style="display:none;">
<p stlye="text-align:center;">Frage 3</p>
<input id="2a" type="radio" name="c" value="dreieins" onclick="checkedvalue('c')"/>
<label for="2a">1</label><br/>
<input id="2b" type="radio" name="c" value="dreizwei" onclick="checkedvalue('c')"/>
<label for="2b">2</label></br>
<input id="2c" type="radio" name="c" value="dreidrei" onclick="checkedvalue('c')"/>
<label for="2c">3</label>
</div>
<div id="finish-button" style="display:none;">
<a class="btn btn-buy" onclick="checkedvalue('finish')">Ergebnis</a>
</div>
JS:
<script>
function checkedvalue(choice){
var eins;
var zwei;
var drei;
if(choice == "a") {
eins = (jQuery('input[name=a]:checked').val());
window.alert(eins);
document.getElementById('schritt1').style.display = 'none';
document.getElementById('schritt2').style.display = 'block';
}
else if(choice == "b") {
zwei = (jQuery('input[name=b]:checked').val());
window.alert(zwei);
window.alert(eins + zwei);
document.getElementById('schritt2').style.display = 'none';
document.getElementById('schritt3').style.display = 'block';
document.getElementById('finish-button').style.display = 'block';
}
else if(choice == "c") {
drei = (jQuery('input[name=c]:checked').val());
}
else if(choice == "finish") {
window.alert(eins + zwei + drei);
if(eins == "eins" && zwei == "zweieins" && drei == "dreieins" )
{
console.log("If 2 works");
window.location.href = "//";
}
}
}
The issue is every time this onclick() method is calling and refreshing the Javascript method.So it will be loose the previously saved values.
You can Collect all the radio Button group values At the time of form submitting using
var eins;
var zwei;
var drei;
declare these variable globally(Outside of all functions) and add below code inside form submit method (write a OnSubmit method in your submit button and write the code inside )
$('input:radio').each(function() {
if($(this).is(':checked')) {
// You have a checked radio button here...
var val = $(this).val();
var name = $(this).attr('name');
if(name=="a")
{
eins=val;
}
else if(name=="b")
{
zwei=val;
}
else
{
drei=val;
}
}
else {
// Or an unchecked one here...
}
});
I didn't test the code,So modify as per your requirements.

how to count check checkboxes in a specific div JAVASCRIPT

I would like to alert the amount of check boxes that are checked in a specific div (not the ones in the <head>!), here is the code :
HTML
<div class="changer">
<label><input id="mode" type="checkbox" name="mode" value="Mode" onclick="mode()" />Mode</label><br />
<label><input id="map" type="checkbox" name="map" value="Map" onclick="map()"/>Map</label><br />
<label><input id="joueurs" type="checkbox" name="joueurs" value="Joueurs" onclick="joueurs()" />Joueurs</label><br />
<label><input id="points" type="checkbox" name="points" value="Points" onclick="points()" />Points</label><br />
</div>
</head>
<body>
<div id="text">
</div>
</body>
<button id="send" onclick="send()">Envoyer</button>
Javascript
function joueurs() {
if((document.getElementById("joueurs").checked == true)) {
joueursall.style.display = 'inline';
text.style.display = 'inline';
}
else {
if((document.getElementById("mode").checked == true)) {
modeall.style.display = 'none';
document.getElementById('mode').checked = false;
}
joueursall.style.display = 'none';
text.style.display = 'none';
}
}
document.getElementById("playerlist").addEventListener("change", function() {
var selected = this.value;
document.getElementById("text").innerHTML = "";
var html = '';
for (var i = 0; i < selected; i++) {
html += '<div class="grpjoueur"> <span class="sub-text">Player</span> <label><input type="checkbox" name="botbot" value="BOT"/>BOT</label </div>';
}
document.getElementById("text").innerHTML = html;
});
Here is the Javascript, it adds 'Joueurs' Dropdownlist if Joueurs is checked and then pop X times something, including a check box, according to the number selected in the Dropdownlist in the #text div
I tried multiple things but always return 0 or all the checkboxes...
In vanilla JS you can use querySelectorAll to query the checkboxes, and then .length to get the number of checkboxes.
var checkboxes = document.querySelectorAll("input[type='checkbox']");
alert(checkboxes.length);
CodePen Demo
If you want to alert only the length of the checked checkboxes, you can query them like this:
var checkedInputs = document.querySelectorAll("input:checked");
alert(checkedInputs.length);
CodePen Demo
when you click on the button, it will alert the number of checked boxes

Categories

Resources