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>
Related
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>
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
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>
I am learning how to do form validation on various types of elements and want to do this in only Javascript. I have some checkboxes here and a Javascript function that checks if the checkboxes has at least one option selected on form submission. Basically the checkboxes should show up red if no option is selected. But I get the error:
Uncaught TypeError: Cannot set property 'borderColor' of undefined
function validate() {
var ok = true;
var yes = document.getElementById("yes").checked
var no = document.getElementById("no").checked;
if (!yes && !no) {
document.getElementsByClassName(".btn-group").style.borderColor = "red";
}
return ok;
}
<div data-toggle="buttons" class="btn-group">
<label class="btn active">
<input id = "yes" type="checkbox" name="box" value="yes" />
</i>Yes
</label>
<label class="btn active">
<input id = "no" type="checkbox" name="box" value="no" />No
</label>
</div>
There are a few problems there:
If you use getElementsByClassName you should use the classname without the dot.
The style property is for the element (while getElementsByClassName returns a list of the elements).
If you only set the color of the border (and not the style and the width) there will be no border.
Here is the correction:
function validate() {
var ok = true;
var yes = document.getElementById("yes").checked
var no = document.getElementById("no").checked;
if (!yes && !no) {
ok = false;
document.getElementsByClassName("btn-group")[0].style.border = '1px solid red';
} else {
document.getElementsByClassName("btn-group")[0].style.border = '';
}
return ok;
}
<div data-toggle="buttons" class="btn-group">
<label class="btn active">
<input id = "yes" type="checkbox" name="box" value="yes" />
Yes
</label>
<label class="btn active">
<input id = "no" type="checkbox" name="box" value="no" />No
</label>
</div>
<button onclick="validate()">Validate</button>
getElementsByClassName() Returns a collection of elements, so you need to iterate over the result to make sure you apply the style change to each element.
Furthermore, you need to use the element.setAttribute() method to change the style like so:
element.setAttribute("style","border-color: red");
Combining those two things should get you the result you want.
Edit: you don't have to use setAttribute() if you don't want to, as Neal pointed out. The important thing to take away is that you need to iterate over your collection.
Edit 2:
Looking at your code again, I noticed that when you call document.getElementsByClassName(".btn-group").style.borderColor = "red";, you're not retrieving the check boxes, you're getting a collection of divs of class btn-group, so you're actually attempting to set the border color of the div to be red, not the check boxes. You're also always returning true unconditionally at the end of validate().
If you're only checking these 2 check boxes, you can just simply use the id's to change them:
function validate() {
var ok = true;
var yes = document.getElementById("yes").checked
var no = document.getElementById("no").checked;
if (!yes && !no) {
document.getElementById("yes").setAttribute("style","border-color: red");
document.getElementById("no").setAttribute("style","border-color: red");
// no checkbox selected, validation should fail and return false
return !ok;
} else {
// checkbox selected, validation should pass and return true
return ok;
}
}
You should add or remove a class to the button group in order to hide show the border. Just add or remove the class when validation changes.
Also, you need to either iterate over all the button group classes or choose one.
Note: I used the class methods from You Might Not Need jQuery.
function validate() {
var btnGroups = document.getElementsByClassName("btn-group");
for (var i = 0; i < btnGroups.length; i++) {
var btnGroup = btnGroups[i];
var yes = document.getElementById("yes")['checked'] == true;
var no = document.getElementById("no")['checked'] == true;
if (!yes && !no) {
if (!hasClass(btnGroup, 'invalid')) addClass(btnGroup, 'invalid');
return false;
} else {
if (hasClass(btnGroup, 'invalid')) removeClass(btnGroup, 'invalid');
}
}
return true;
}
function hasClass(el, className) {
if (el.classList) return el.classList.contains(className);
else return new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
}
function addClass(el, className) {
if (el.classList) el.classList.add(className);
else el.className += ' ' + className;
}
function removeClass(el, className) {
if (el.classList) el.classList.remove(className);
else el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
.btn-group.invalid {
border : thin solid red;
}
<div data-toggle="buttons" class="btn-group">
<label class="btn active">
<input type="checkbox" id="yes" name="box" value="yes" onchange="validate()" />Yes
</label>
<label class="btn active">
<input type="checkbox" id="no" name="box" value="no" onchange="validate()" />No
</label>
</div>
I have two checkboxes in a group and one text input. If one (or both) of the checkboxes are selected I need to have the text input be required, as well as if the text input has text I need at least one of the checkboxes to be required. Another problem I'm having it that it's using a custom templating engine (PHP backend) and is a pain to configure and get the attributes correct, another issue is it's all referenced by the name attribute and this is why I'm using a HTML5 data-group for the checkbox options which I think it working.
Any help in getting this to work, combining functions (if this makes it easier/simpler).
BTW it's running 1.3.2 jQuery
Example: (not working)
http://jsfiddle.net/NYn8e/1/
Any suggestions?
JS:
function checkboxSelectedRequiredAdditionalFields(elem) {
var passedElement = $('input:checkbox[name=' + elem + ']');
passedElement.click(function() {
$('input[name=number]').attr('required', true).append('<span class="required">*</span>');
alert('text is required now?');
});
}
function numberEnteredRequiredAdditionalFields(elem) {
var passedElement = $('input[name=' + elem + ']');
if (passedElement.val().length > 0) {
var boxes = $('input[data-group=cbOptions]').click(function() {
boxes.not(this).attr('required', false);
alert('checkbox is selected so other checkbox is not required');
});
$('input[data-group=cbOptions]').each(function() {
$(this).attr('required', true).next().append('<span class="required">*</span>');
alert('checkbox is required now?');
});
}
}
HTML
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox1');" data-group="cbOptions">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox2');" data-group="cbOptions">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" onclick="numberEnteredRequiredAdditionalFields('number');">
</b>
</form>
You should separate the JavaScript from the HTML. Fiddle: http://jsfiddle.net/NYn8e/6/. If possible, remove <b> from the HTML source, and extend the style sheet with the right CSS property: font-weight: bold;.
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" data-required="checkbox">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" data-required="checkbox">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" data-required="number">
</b>
</form>
JavaScript:
function required(){
//Any checked checkbox? checked == 0 = no, otherwise: yes
var checked = $('input[data-required=checkbox]:checked').length;
var $checkboxes = $('input[data-required=checkbox]');
var $num = $('input[name=number]');
var length = $num.val().length;
//Remove previously added span, if existent.
$num.next('span.required').remove();
$checkboxes.next('span.required').remove();
if(!length && checked){
$num.after('<span class="required">*</span>');
alert("Number required!");
} else if(length && !checked){
$checkboxes.after('<span class="required">*</span>');
alert("Check at least one checkbox.");
}
}
$(document).ready(function(){
$("[data-required]").change(required);
});
=) Would this one help you?
<form id='myForm'>
<input type='checkbox' name='checkbox1' value='t' id='checkbox1' onchange='alertUser()' />
<input type='checkbox' name='checkbox2' value='t' id='checkbox2' onchange='alertUser()' />
<input type='text' name='number' id='number' onchange='alertUser()'/>
</form>
<script type='text/javascrip>
function alertUser() {
var checked1 = $('#checkbox1').attr('checked');
var checked2 = $('#checkbox2').attr('checked');
var number = $('#number').val();
if ((checked1 == true || checked2 == true) && number == '') {
alert('Number is required!');
} else if (number != '' && (checked1 != true && checked2 != true)) {
alert('One of the checkbox need to be checked!');
}
});
</script>
This should hopefully give you an idea on how to accomplish the task. http://jsfiddle.net/NYn8e/8/
var $textbox = $('input[name=number]').hide();
$('input[type=checkbox]').change(function() {
var $this = $(this); //store jquery object
//get the other checkbox
var $other= ($this.attr('name') === 'checkbox1') ? $('input[name=checkbox2]') : $('input[name=checkbox1]');
if (!$other.is(':checked') && !$this.is(':checked')) {
$textbox.val('').hide();
} else{
$textbox.show();
}
});