Several input checkbox using one JS with different var - javascript

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>

Related

Div not showing when radio button checked

I have a radio button that will show a div with an input text when it is checked 'NO'. But it is not showing the div, however when I play around the radio button then the div will show. Where am I missing?
function CheckboxCheck(checkbox) {
var firstCheckbox = document.getElementById('check1');
var secondCheckbox = document.getElementById('check2');
var rmk = document.getElementById("rmk");
if (firstCheckbox.checked == true) {
rmk.style.display = "none";
} else if (secondCheckbox.checked == true) {
rmk.style.display = "block";
document.getElementById("rmk").required = true;
}
}
<div>
<label>Have you registered the course?</label>
<table border=0>
<tr>
<td>YES </td>
<td><input type="radio" name="register" value="Y" id="check1" onclick="CheckboxCheck('first')">  </td>
<td>NO </td>
<td><input type="radio" name="register" value="N" checked id="check2" onclick="CheckboxCheck('second')"></td>
</table>
</div>
<div id="rmk" style="display:none">
<label>Reasons</label>
<input type="text" name="remarks" class="form-control">
</div>
There are a few structure and accessibility proposals going on in this suggestion but I think strictly speaking, the easiest solve for you is to invoke the function on page load. Give this example a look:
function CheckboxCheck(checkbox) {
var firstCheckbox = document.getElementById('check1');
var secondCheckbox = document.getElementById('check2');
var rmk = document.getElementById("rmk");
var rmkdiv = document.getElementById("rmk-div");
if (firstCheckbox.checked == true) {
rmkdiv.style.display = "none";
} else if (secondCheckbox.checked == true) {
rmkdiv.style.display = "block";
rmk.required = true;
}
}
CheckboxCheck()
<div>
<p>Have you registered the course?</p>
<label>
YES<input
type="radio"
name="register"
value="Y"
id="check1"
onclick="CheckboxCheck()"
/></label>
<label>NO
<input
type="radio"
name="register"
value="N"
checked
id="check2"
onclick="CheckboxCheck()"
/>
</label>
<div id="rmk-div" style="display: none">
<label>Reasons</label>
<input id="rmk" type="text" name="remarks" class="form-control" />
</div>
</div>
Your input field will only be visible when the function CheckboxCheck is executed. Since "NO" is checked from the beginning, the function will not be executed because it is only called when a change takes place.

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>

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.

Checkbox onchange show div and cheked another checkbox

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>

Checkbox arrays

Just wondering if anyone can help. I currently have code like this:
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Each 'section' is dynamically produced. How do I go about inserting the value of each input into the span of each section when checked. I have been playing around with Arrays but stumbling due to each section being produced dynamically.
Can any of you help me out?
Better give each checkbox input a value, anyway, I'll use id instead.
// Listen to all checkboxes
$('section input[type="checkbox"]').click(function(e) {
var $this = $(e.target);
// Find the container of same group.
var $parent = $this.parent('section');
// Find all checked ones.
var checked = $parent.find('input[type="checkbox"]:checked');
// Map the value or id, to an array.
var result = $.map(checked, function(ele) {
return $(ele).attr('id');
});
// Get the result, use it whatever you want.
$parent.find('.tags').text(result.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Use this javascript:
<script type="text/javascript">
window.addEventListener("load",function(){
var sections = document.getElementsByTagName("section");
for(var i=0; i<sections.length; i++){
var n = 0;
sections[i].span = sections[i].getElementsByTagName("span")[0];
sections[i].checkboxes = [];
var inputs = sections[i].getElementsByTagName("input");
for(var c=0; c<inputs.length; c++){
if(inputs[c].type!="checkbox"){continue}
sections[i].checkboxes[n++]=inputs[c];
inputs[c].onchange=function(){this.parentNode.getValues();}
}
sections[i].getValues = function(){
var o=[], n=0;
for(var i=0; i<this.checkboxes.length; i++){if(this.checkboxes[i].checked){o[n++] = this.checkboxes[i].id;}}
this.span.innerHTML = o.join(", ");
};
}
},false);
</script>

Categories

Resources