I have:
<label><input type="checkbox" name="all"> text</label>
<label><input type="checkbox" name="js-frameworks"> text</label>
const all = document.getElementsByName('all')[0];
const jsFrameworks = document.getElementsByName('js-frameworks')[0];
this.addEventListener("change", function() {
if (all.checked) {
jsFrameworks.parentNode.className = 'readonly';
}
});
I thought that when I deselect the checkbox the class 'readonly' will be removed as the code executes only when I tick the checkbox giving the if condition is true. I can't seem to escape the if condition, so to kind of toggle between the click and unclick. How can I do that?
Thanks
Change it this way:
this.addEventListener("change", function() {
if (all.checked) {
jsFrameworks.parentNode.className = 'readonly';
} else {
jsFrameworks.parentNode.className = '';
}
});
This way you are removing the class when unchecked.
UPDATE:
Or you could save the classes that your element may have before:
let classesBefore = jsFrameworks.parentNode.className;
this.addEventListener("change", function() {
if (all.checked) {
jsFrameworks.parentNode.className = classesBefore + ' readonly';
} else {
jsFrameworks.parentNode.className = classesBefore;
}
});
Try this.
const all = document.getElementsByName("all")[0];
const jsFrameworks = document.getElementsByName("js-frameworks")[0];
this.addEventListener("change", function() {
if (all.checked) {
jsFrameworks.parentNode.classList.add("readonly");
} else if (!all.checked) {
jsFrameworks.parentNode.classList.remove("readonly");
}
});
Try this
this.addEventListener("click", function() {
this.parentNode.toggle('readonly');
}
Related
I want to uncheck a checkbox using javascript. I have one button which just unchecks the box and works fine:
function clear() {
document.getElementById("check").checked = "";
}
I have another button that I want to check the box if not checked and uncheck if it is. Below doesn't uncheck the box. I can can switch the if statement and does works the opposite way. What's the problem?
function switchIt() {
if (document.getElementById("check").checked !== "checked") {
document.getElementById("check").checked = "checked";
} else {
document.getElementById("check").checked = "";
}
Thanks!
switch is a reserved word, use another one
function switchIt() {
var box = document.getElementById("check");
if (box.checked) {
box.checked = false;
} else {
box.checked = true;
}
}
setInterval(switchIt, 1000);
<input type="checkbox" id="check" />
Treat "checked" as a boolean, not as a string.
You can just invert it, as in
element = document.getElementById("check")
element.checked = !element.checked
A more featured example:
var $toggle = document.getElementById('toggle');
var $checkbox = document.getElementById('checkbox');
var toggle_checkbox = function() {
$checkbox.checked = !checkbox.checked;
}
$toggle.addEventListener('click',toggle_checkbox);
<label>
Checkbox:
<input id="checkbox" type="checkbox" checked />
</label>
<button id="toggle">Toggle</button>
You need a boolean to do that.
Take a look at this pen:
https://codepen.io/anon/pen/jJyXgO
let checkbox = document.querySelectorAll('#check')[0]
setInterval(function() {
checkbox.checked = !checkbox.checked
}, 1000)
I've never seen it done with a string "checked" before. Try with a boolean like:
function change() {
if (document.getElementById("check").checked !== true) {
document.getElementById("check").checked = true;
} else {
document.getElementById("check").checked = false;
}
}
or easier
function change() {
document.getElementById("check").checked = !document.getElementById("check").checked
}
Don't forget, switch is reserved, so use a different name, as I did with change()
I'm a librarian working on improving my library's main search feature. I am trying to get a checkbox labeled "Everything" to check automatically if users deselect all of the other options ("books," "articles," "music," "videos".)
Here's the relevant javascript:
$(document).ready(function() {
var $others = $('input[class="checkoption"]').not('#everythingbox')
$others.change(function() {
if (this.checked==false) {
$('#everythingbox').prop('checked', true)
}
});
});
I almost have it working, but there's a problem: if I select two or more choices and deselect one, "Everything" checks automatically, but I only want it to check automatically if none of the others are checked.
Here is the full fiddle: https://jsfiddle.net/kr0syfn3/11/
I've edited your fiddle. You basically need to check all the other check boxes when a change happens and update the everything box accordingly.
Here's the updated fiddle jsfiddle.net/john_lay/kr0syfn3/12/
Apologies in advance for commenting out some of your code, but there was a lot of repetition. Finally you should add your change events inside the $(document).ready(function() {}); handler.
You are going to need to inspect all checkboxes each time any one of them is clicked. Right now, you are just inspecting the one single one that is clicked. To inspect all of them, you will need to use a loop (I'm using the each function in my sample below), and you might have to change your logic just a bit because you are now inspecting all items:
$(document).ready(function() {
var $others = $('input[class="checkoption"]').not('#everythingbox');
$others.change(function() {
var othersToCheck = $('input[class="checkoption"]').not('#everythingbox');
var anyChecked = false;
$.each(othersToCheck, function(index) {
if ($(this).checked) {
anyChecked=true;
}
});
$('#everythingbox').prop('checked', !anyChecked)
});
});
You could try selecting all the checkboxes that are selected and then comparing the lists, to see if all checkboxes have been selected? E.g.
var $others = $('input[class="checkoption"]').not('#everythingbox')
$others.change(function() {
var $checked = $('input[class="checkoption"]:checked').not('#everythingbox')
if ($checked.length != $others.length) { //not all the boxes are checked
$('#everythingbox').prop('checked', true)
}
}
Hope this helps!
The most concise answer to this would be to leverage the power of jQuery's built in selectors, like so:
You will also want to handle if the user selects the everything checkbox manually by clearing the rest of the selected checkboxes.
$(document).ready(function() {
var $inputs = $('input.checkoption');
$inputs.on("change", function() {
if ($(this).attr("id") !== "everythingbox") {
$('#everythingbox').prop('checked', !$('input.checkoption:not(#everythingbox):checked').length)
} else {
$inputs.not("#everythingbox").prop("checked", false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1<input type="checkbox" class="checkoption" /> 2
<input type="checkbox" class="checkoption" /> 3
<input type="checkbox" class="checkoption" /> 4
<input type="checkbox" class="checkoption" /> everything
<input type="checkbox" class="checkoption" id="everythingbox" checked/>
var $others = $('input[class="checkoption"]').not('#everythingbox')
console.log($others)
$('#everythingbox').change(function () {
if (this.checked) {
$others.prop('checked', false)
$('#everythingbox').attr('disabled', true);
}
});
$others.change(function () {
var check = false;
var l = $others.length;
for (var i = 0; i < l; i++) {
if ($others[i].checked) {
check = true;
}
}
if (check) {
$('#everythingbox').attr('disabled', false);
$('#everythingbox').prop('checked', false);
} else {
$('#everythingbox').attr('disabled', true);
$('#everythingbox').prop('checked', true);
}
})
var music1 = $("input[id='musiccheck']");
var music2 = $("input[id='musicscores']");
music1.on('change', function () {
music2.prop('checked', this.checked);
});
music1.on('change', function () {
music2.prop('unchecked', this.unchecked);
});
$(document).ready(function () {
});
I am seeing how I can make an Are You Human checkbox, but I am having a problem (Code At The End). I am trying to make it see if it is clicked until it is clicked. I tried onclick, but that is not working.
window.onload = function() {
var input = document.getElementById('ruhuman');
function check() {
if (input.checked) {
ruhuman.checked = true;
if (event.originalEvent === undefined) {
ruhuman.human = false;
} else {
ruhuman.human = true;
}
}
alert(ruhuman.human);
alert(ruhuman.checked);
}
input.onchange = check;
check();
}
<input type="checkbox" id="ruhuman" class="ruhuman" onclick="check()" required="required">
<label>R U Human?</label>
Edit: Thanks for your help! Finished product at http://ruhuman.github.io/.
To the people that answered I can put your github for your help!
originalEvent is JQuery, not JavaScript. A workaround is to test screenX and screenY -- if it's a human, these will have some value based on the checkbox position. Also, you can remove the onclick from your html and tie your click event like this:
document.getElementById ("ruhuman").addEventListener("click", function(e){
if (this.checked) {
ruhuman.checked = true;
if (e.screenX && e.screenY) {
ruhuman.human = true;
} else {
ruhuman.human = false;
}
}
console.log(ruhuman.human);
console.log(ruhuman.checked);
});
JS Fiddle Demo
This works: https://jsfiddle.net/rz4pmp5L/3/
var input = document.getElementById('ruhuman');
var ruhuman =
{
checked: false
};
function check()
{
if (input.checked)
{
ruhuman.checked = true;
}
alert(ruhuman.checked);
}
input.onchange = check;
check();
The problem was (at least) that ruhuman was not defined at all.
I'm trying to add a "disabled" class to my button when all the checkboxes are checked and when none of them are checked.
Was able to figure out when none of them are check:
var SummaryCheckBox = function() {
$(':checkbox').click(function () {
$('.btn-primary').toggleClass('disabled', !$(':checkbox:checked').length);
});
}
But having a hard time checking when all the checkboxes are checked. Suggestions?
$(":checkbox").change(function(){
var a = $(":checkbox");
if(a.length == a.filter(":checked").length){
alert('all checked');
}
if(!a.length == a.filter(":checked").length){
alert('all unchecked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>
This will remove class disabled if all checkboxes are checked or add it if only one checkbox not checked:
var SummaryCheckBox = function() {
$(':checkbox').click(function () {
$('.btn-primary').toggleClass('disabled', !($(':checkbox:checked').length === $(':checkbox').length));
});
}
var SummaryCheckBox = function() {
$(':checkbox').click(function () {
if($(':checkbox:checked').length == $(':checkbox').length || !$(':checkbox:checked').length){
$('.btn-primary').toggleClass('disabled');
}
});
}
Also you might wanna add some class to checkboxes
Add an additional condition to compare lengths,
$(':checkbox:checked').length === $(':checkbox').length
// ^Checked length ^Total Length
var SummaryCheckBox = function() {
$(':checkbox').click(function () {
$('.btn-primary').toggleClass('disabled', $(':checkbox:checked').length === $(':checkbox').length || !$(':checkbox:checked').length);
});
}
Also, binding a click handler inside a function is not so good idea. Any specific reason for this? Move the .click(..) outside the function.
Fiddle
Fiddle2 with click handler outside the function
function allChecked() {
return $('input[type=checkbox]').not(':checked').length == 0;
}
You can check if it returns true or false, toggle the class you want.
jsfiddle DEMO
$('[type="checkbox"]').on('change', function(){
var l = $('[type="checkbox"]:checked').length;
if(l === 4 || l === 0){
$('[type="submit"]').attr('disabled', '');
} else {
$('[type="submit"]').removeAttr('disabled');
}
});
Digit 4 (number of checkboxes) is hardcoded for simplicity.
Fiddle
Try this code:
$(':checkbox').click(function () {
$('.btn-primary').toggleClass('disabled', !$(':checkbox:checked').length === $(":checkbox").length);
});
You need to check whether checked check boxes are same as total number of check boxes, Then you can add disabled class to the button.
Demo
my two cents will be example code that features a larger code base but tries to be more generic and self-documenting too ...
(function (global, $) {
var
Array = global.Array,
array_from = (
((typeof Array.from == "function") && Array.from)
|| (function (array_prototype_slice) {
return function (list) {
return array_prototype_slice.call(list);
};
}(Array.prototype.slice))
),
isCheckboxControl = function (elm) {
return !!(elm && (elm.type == "checkbox"));
},
isControlChecked = function (elm) {
return !!(elm && elm.checked);
},
validateSubmitState = function (evt) {
var
elmForm = evt.currentTarget.form,
$btnPrimary = $(elmForm).find(".btn-primary"),
checkboxList = array_from(elmForm.elements)
.filter(isCheckboxControl),
isEveryCheckboxChecked = checkboxList
.every(isControlChecked),
isSomeCheckboxChecked = checkboxList
.some(isControlChecked)
;
if (isEveryCheckboxChecked || !isSomeCheckboxChecked) {
$btnPrimary.attr("disabled", "");
} else {
$btnPrimary.removeAttr("disabled");
}
},
initializeSubmitBehavior = function () {
var
$btnPrimary = $(".btn-primary")
;
$btnPrimary // register validation.
.closest("form")
.on("click", ":checkbox", validateSubmitState)
;
// force initial validation.
$btnPrimary.toArray().forEach(function (elmButton) {
var
elmCheckbox = $(elmButton.form).find(":checkbox")[0]
;
if (elmCheckbox) { // initial validation by fake event.
validateSubmitState({currentTarget:elmCheckbox});
}
// just trying not to break this examples form.
elmButton.form.action = global.location.href;
});
}
;
initializeSubmitBehavior();
}(window, jQuery));
I have the following mark-up:
$(document).ready(function () {
$('.lalala').bind('blur', function (e) {
CheckFirstInput($(this));
});
});
<div id="divContainer">
<input type="text" class="lalala" />
<p id="img1"></p>
</div>
And the following script
function CheckFirstInput(element) {
var txtLength = element.val();
var parent;
var lastElement;
if (txtLength.length < 1) {
parent = element.parent();
lastElement = parent.last();
lastElement.text('prazno e');
}
else {
//element.parent().lastChild().text('4884384f384r34rf');
parent = element.parent();
lastElement = parent.last();
lastElement.text('ne e prazno');
}
}
If the input field is not empty I want to select the last element of the wrapping div (<p>) and change its text. How do I do that?
Thanks in advance!!
You needed to select the children() of the element's parent. You were selecting the last parent. (Which is the parent.)
The following is working. I also cleaned up the code a bit.
$('.lalala').blur( function () {
CheckFirstInput($(this));
});
function CheckFirstInput(element) {
if (element.val().length < 1) {
element.siblings(':last').html('prazno e');
}
else {
element.siblings(':last').html('ne e prazno ');
}
}
Working Fiddle
http://jsfiddle.net/CRccw/2/
If i got it right you could check $(element).is(":empty") and use parent.siblings(":last-child")
Your question has been answered, but here is another way to do it:
$('.lalala').bind('blur', function (e) {
CheckFirstInput($(this));
});
function CheckFirstInput($el) {
var $last = $el.siblings().filter(':last');
var html = ($el.val() == '') ? 'prazno e' : 'ne e prazno';
$last.html(html);
}
DEMO