toggle checkbox with javascript - javascript

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()

Related

How do I make sure in JavaScript that when I click on any checkbox, the input field goes to 0

How do I make sure that when I click on any checkbox, the input field goes to 0. Because now it works with the first, but not with the others.
This is the code I have now:
let checkbox = document.getElementById("abs");
let inp = document.getElementById("cijfer");
checkbox.addEventListener('change', function() {
if (this.checked) {
inp.value = 0;
}
});
The first input field does go to 0, but the second one does not.
Picture of the problem:
Checkbox and input code in gohtml:
<td><input id="cijfer" type="number" name="grade-{{$s.ID}}" step="0.1" min = "0" max = "10" value="{{(index $.Grades $s.ID).Value}}"></td>
<td>
<input id="abs" type="checkbox" name="abs-{{$s.ID}}">
<label for="abs">ABS</label>
</td>
you are using id (getElementById) and it's an unique attribute!
use "abs" class and "cijfer" class instead!
then find the closest input and make the value zero!
<script>
function closest(el, classname) {
if(el.parentNode){
if(el.parentNode.className.includes(classname)){
return el.parentNode;
}
else{
return closest(el.parentNode, classname);
}
}
else{
return false;
}
}
document.querySelectorAll('.abs').forEach(function(item) {
item.addEventListener('change', function() {
if (this.checked) {
let closest = closest(this, 'cijfer');
closest.value = "0";
}
}
});
</script>
this was pure js!
you may use jquery instead:
$('.abs').on('change', function(){
$(this).prev('input').val('0');
});

How to extract this function to not duplicate code

This code checks if the checkbox is enabled on site if it is disabled then it disable the textbox.
Function disableTextBox() is a onclick function and the $(function() is used to check the behavior of the checkbox after refreshing the page, I did not use the localstorage for that because sometimes different browsers are used.
How can I write this code better to do not duplicate it?
If the checkbox is checked then the textbox should be enabled, if the checkbox is not checked then the checkbox should be disabled for any input. It saves the checkbox after clicking save button (that is different functionality) not connected with this problem, and when the user back to the page it should check if the checkbox is checked or not and adjust the textfield.
Any ideas how to write it better or something?
$(function()
{
var checkboxField = document.querySelector('#checkbox');
var textBox = document.querySelector('#textBox');
if (checkboxField.checked == true)
{
textBox.disabled = false;
}
else if (checkboxField.checked == false)
{
textBox.disabled = true;
}
});
function disableTextBox()
{
var checkboxField = document.querySelector('#checkbox');
var textBox = document.querySelector('#textBox');
if (checkboxField.checked == false)
{
textBox.disabled = true;
}
else if (checkboxField.checked == true)
{
textBox.disabled = false;
}
}
Call your disableTextBox() function, and instead of the if/else you could use the evaluated boolean result of checkboxField.checked straight ahead:
function disableTextBox() {
var checkboxField = document.querySelector('#checkbox');
var textBox = document.querySelector('#textBox');
textBox.disabled = !checkboxField.checked;
}
jQuery(function( $ ) {
// Do it on DOM ready
disableTextBox();
// and on button click
$('#btnDisableTextBox').on('click', disableTextBox);
// Other DOM ready functions here
});
prefering this way ;)
in this story every thing is boolean
Don't do testing if a boolean is True to déclare a true value for a if...
const
checkboxField = document.querySelector('#checkbox'),
textBox = document.querySelector('#textBox');
checkboxField.onchange = function()
{
textBox.disabled = !checkboxField.checked;
}
<label> modify texy <input type="checkbox" id="checkbox" checked>
<textarea id="textBox"disable> blah blah bla</textarea>

See if check box is clicked until it is clicked

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.

to add a class when all checkboxes are checked

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));

Javascript check if radio button was checked?

I have found scripts that do it, but they only work with one radio button name, i have 5 different radio button sets. How can i check if its selected right now i tried on form submit
if(document.getElementById('radiogroup1').value=="") {
alert("Please select option one");
document.getElementById('radiogroup1').focus();
return false;
}
does not work.
If you have your heart set on using standard JavaScript then:
Function definition
var isSelected = function() {
var radioObj = document.formName.radioGroupName;
for(var i=0; i<radioObj.length; i++) {
if( radioObj[i].checked ) {
return true;
}
}
return false;
};
Usage
if( !isSelected() ) {
alert('Please select an option from group 1 .');
}
I'd suggest using jQuery. It has a lot of selector options which when used together simplify the much of the code to a single line.
Alternate Solution
if( $('input[type=radio][name=radioGroupName]:selected').length == 0 ) {
alert('Please select an option from group 1 .');
}
var checked = false, radios = document.getElementsById('radiogroup1');
for (var i = 0, radio; radio = radios[i]; i++) {
if (radio.checked) {
checked = true;
break;
}
}
if (!checked) {
alert("Please select option one");
radios.focus();
return false;
}
return true;
A very simple function is:
<script type="text/javascript">
function checkRadios(form) {
var btns = form.r0;
for (var i=0; el=btns[i]; i++) {
if (el.checked) return true;
}
alert('Please select a radio button');
return false;
}
</script>
<form id="f0" onsubmit="return checkRadios(this);">
one<input type="radio" name="r0"><br>
two<input type="radio" name="r0"><br>
three<input type="radio" name="r0"><br>
<input type="submit">
</form>
However, you sould always have one radio button selected by default (i.e. with the select attribute), some user agents may automatically select the first button. Then you just need to check if the default (usually the first one) is checked or not.
Why don't just use a oneliner?
I wrote this code, it will submit the form if at least one radio is checked:
(function(el){for(var i=el.length;i--;) if (el[i].checked) return el[i].form.submit()||1})(document.form_name.radio_name)||alert('please select item')
Otherwise it will make an alert. Or you may also modify it to use with form's onsubmit:
return (function(el){for(var i=el.length;i--;) if (el[i].checked) return 1})(document.form_name.radio_name)||alert('please select item')
Just replace form_name and radio_name accordingly.
See how it works: http://jsfiddle.net/QXeDv/5/
Here's a good tutorial -> http://www.somacon.com/p143.php
// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
if(!radioObj) return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked) return radioObj.value;
else return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) return radioObj[i].value;
}
return "";
}
// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
if(!radioObj) return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) radioObj[i].checked = true;
}
}
Are you ok with jquery? If so:
$(document).ready(function(){
if($('input[type=radio]:checked').length == 0)
{
alert("Please select option one");
document.getElementById('radiogroup1').focus();
return false;
}
}

Categories