Loop through checkboxes and conditionally disable unchecked - javascript

I'm trying to write a basic function in pure JS that simply checks the number of checked checkboxes, and if that number exceeds a certain amount, disables the rest. I can achieve this easily in jQuery, but trying to get it working in pure JS. I have a CodePen set up here and I'm including my working JS below. Thanks for any insight here.
(function() {
var checkboxes = document.querySelectorAll('input[id^="mktoCheckbox"]');
var active = document.querySelectorAll('input[id^="mktoCheckbox"]:checked');
var numActive = active.length;
console.log(numActive);
if (numActive > 1) {
for(var i = 0; i < checkboxes.length; i++){
if (checkboxes[i].checked == true) {
return;
} else {
checkboxes[i].disabled == true;
}
}
}
})();

There are two problems in your code:
You're returning from the if condition, which causes the loop to terminate.
You're not assigning true to disabled attribute, instead you're comparing with ==.
Change the related snippet to the following to make it work:
if (numActive > 1) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked != true) {
checkboxes[i].disabled = true;
}
}
}
You can find a working fork of your pen here. Following is a working SO snippet:
(function() {
var checkboxes = document.querySelectorAll('input[id^="mktoCheckbox"]');
var active = document.querySelectorAll('input[id^="mktoCheckbox"]:checked');
var numActive = active.length;
console.log(numActive);
if (numActive > 1) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked != true) {
checkboxes[i].disabled = true;
}
}
}
})();
<fieldset>
<legend>Choose some monster features</legend>
<div>
<input type="checkbox" id="mktoCheckbox_1" name="feature" value="scales" checked />
<label for="scales">Scales</label>
</div>
<div>
<input type="checkbox" id="mktoCheckbox_2" name="feature" value="horns" />
<label for="horns">Horns</label>
</div>
<div>
<input type="checkbox" id="mktoCheckbox_3" name="feature" value="claws" />
<label for="claws">Claws</label>
</div>
<div>
<input type="checkbox" id="mktoCheckbox_4" name="feature" value="tails" checked />
<label for="tails">Tails</label>
</div>
</fieldset>

Here's a working pen.
First of all, imo, you should use getAttribute and setAttribute on DOM elements. HTMLInputElement.checked afaik only reflects the checked attribute (and converts it to boolean) for convenience.
With that in mind, you need to now test against strings with the strict comparison operator ===. E.g.
if(checkbox.getAttribute('checked') === 'true') {...}
since using == would evaluate to false
true == 'true' // false
Also, instead of the for loop you can make use the for-of loop on DOM collections. I.e. this works:
const checkboxes = document.querySelectorAll('...');
for(const checkbox of checkboxes) {
...
}
Keep in mind that you use continue and break to control the loop and not return.

Related

Checkbox State Persistence before and after form submission

I am new to web developing. Apologies, if this is too simple but could not find the right way to fix this issue.
I have been asked to make a simple form with several checkboxes having a unique name and different values.
No problem for that. The issue I am encountering is that I have also been asked that I need to have all the checkboxes checked by default before submission and only to keep the checkboxes that remain checked, checked after the form submission. My code below does not make them all checked by default but save the results after form submission. Even adding the statement checked on the input tag does not change much.
<form onsubmit="return saveCheckboxValue();">
<label for="checkbox1">Option 1</label>
<input type="checkbox" id="checkbox1">
<br>
<label for="checkbox2">Option 2</label>
<input type="checkbox" id="checkbox2">
<br>
<label for="checkbox3">Option 3</label>
<input type="checkbox" id="checkbox3">
<br>
<input type="submit" value="Submit">
</form>
<script>
function saveCheckboxValue() {
// Get all checkbox elements
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
localStorage.setItem(checkboxes[i].id, true);
} else {
localStorage.removeItem(checkboxes[i].id);
}
}
return true;
}
window.onload = function() {
// Get all checkbox elements
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = JSON.parse(localStorage.getItem(checkboxes[i].id)) || false;
}
};
</script>
I tried to change the value to true
> window.onload = function() { // Get all checkbox elements var
> checkboxes = document.querySelectorAll("input[type='checkbox']");
>
> for (var i = 0; i < checkboxes.length; i++) {
> checkboxes[i].checked = JSON.parse(localStorage.getItem(checkboxes[i].id)) || true; } };
But by doing this, the checkboxes will be checked by default which is good, but if I uncheck some and submit the form, even the unchecked ones will be checked after the form submission.
From what I understood you want the boxes to be checked by default only at the first load, then the values to be persistent.
Would that work for you ?
in the saveCheckboxValue function, change the else condition to set the item to false instead of deleting it.
window.onload = function () {
// Get all checkbox elements
var checkboxes = document.querySelectorAll("input[type='checkbox']");
var val;
for (var i = 0; i < checkboxes.length; i++) {
val = JSON.parse(localStorage.getItem(checkboxes[i].id))
if (val == null) {
checkboxes[i].checked = true;
} else{
checkboxes[i].checked = val;
}
}
};

validation on checkbox not working

I am building a project on attendance management. In one of the forms of my project, I have multiple checkboxes. I want that at least one checkbox must be checked for form submission. I tried with Javascript but the problem is, it flag an alert even if one or more checkbox is checked.
Here is my js code :
function validat(){
var a = document.getElementsByTagName("checkbox");
var bool=false;
for(var i=0;i<a.length;i++){
if(a[i].checked==true){
bool=true;
}
}
if(bool){
return true;
}
else{
alert("Sorry!Please select checkbox corresponding to students involved in duty leaves.");
return false;
}
Here's my checkbox code :
echo "<input type='checkbox' name=duty[]' value='$row[university_roll_no]'></td></tr>";
Since you need at least one checkbox to be checked you don't have to loop through all the checkboxes in your form. In the first found checkkbox you can stop.
function validat(){
var checkboxes = document.getElementsByTagName("checkbox");
var atLeastOneCheckBoxIsChecked = false;
for( var i = 0; i < checkboxes.length; i++ ){
if( checkboxes[i].checked == true ){
atLeastOneCheckBoxIsChecked = true;
break;
}
}
if(atLeastOneCheckBoxIsChecked){
return true;
}
else {
alert("Sorry!Please select checkbox corresponding to students involved in duty leaves.");
return false;
}
}
A more functional way to do the same thing, is to be use Array.prototype.some method:
function validat(){
var atLeastOneCheckBoxIsChecked = document.getElementsByTagName("checkbox")
.some(checkbox => checkbox.checked == true);
if(atLeastOneCheckBoxIsChecked){
return true;
}
else {
alert("Sorry!Please select checkbox corresponding to students involved in duty leaves.");
return false;
}
}
Here you have an example:
function check() {
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
if (!checkedOne) {
console.log('please check at least one box!');
}
console.log(checkedOne);
}
<fieldset>
<legend>Choose some monster features</legend>
<div>
<input type="checkbox" id="scales" name="feature" onClick=check()
value="scales" checked />
<label for="scales">Scales</label>
</div>
<div>
<input type="checkbox" id="horns" name="feature" onClick=check()
value="horns" />
<label for="horns">Horns</label>
</div>
<div>
<input type="checkbox" id="claws" name="feature" onClick=check()
value="claws" />
<label for="claws">Claws</label>
</div>
</fieldset>
You need to get input elements and check if type is "checkbox":
var a = document.getElementsByTagName("input");
for(var i = 0; i < a.length; i++) {
if(inputs[i].type == "checkbox") {
if (inputs[i].checked) {
bool=true;
}
}
}
Change your line
var a = document.getElementsByTagName("checkbox");
to
var a = document.querySelectorAll('input[type="checkbox"]');
I would have preferred you to use jQuery but with what you currently have, you need to do this:
var a = document.getElementsByTagName("input");
And then:
if(a[i].type == 'checkbox' && a[i].checked==true){
// Checked alert
}

check if selected option and checkbox is checked

I have some problems here with javascript.
I want someone to choose an option and a checked box, and if both are checked then other checkboxes should not be able to click.
I had tried to give the function 2 parameters (one is for the option and one for the checkbox).
function bs(id /*,chbxvalue */ )
{
var selectElement = document.getElementById(id);
var selectValue = selectElement.options[selectElement.selectedIndex].value;
//var select2Element = document.getElementById(chbxvalue);
//var selectCHBXval = select2Element.options[select2Element.selectedIndex].value;
if((selectValue == "banana" ) /*&& (document.getElementById("apple").checked == true )*/ )
{
document.getElementById("juice").checked = true;
}
else if(selectValue == "Salad")
{}
}
The thing in the comments doesn't work.
<div id="flavor"><br />
<select id="bss" name="beh" onChange="bs('bss')">
<option value="banana" >banana</option>
<option value="pinapple" >pinapple</option>
</select>
</div>
<div id="divcontainer" class="cont" style="display:block;">
<input type="checkbox" name="app" id="apple" value="appl" />Apples <br />
<input type="checkbox" name="juices" id="juice" value="fj" />Fruitjuice <br />
</div>
I've changed the names here. Has anybody an idea? Sorry, I am not so good with javascript... .
Sounds like you'd like to use simply
document.getElementById("...").disabled=true;
Or if you'd like to disable more checkboxes at once, assign them a class, and use
elements = document.getElementsByClassName("my_class");
for(var i = 0; i < elements.length; ++i)
{elements[i].disabled = "true"; }
I'm not exactly sure if this is what you're after, but it seems like you want some kind of conditional logic. I made a fiddle to illustrate it: https://jsfiddle.net/75uLereo/
var radios = document.myform.type,
select = document.myform.flavor;
for(var i = 0; i < radios.length; i++){
radios[i].addEventListener('change', checkValues);
}
select.addEventListener('change', checkValues);
function checkValues(){
var select = document.myform.flavor,
selectedValue = select.options[select.selectedIndex].value,
radioValue = document.querySelector('input[name = "type"]:checked').value;
if(radioValue !== "undefined"){
switch(selectedValue){
case 'none':
case 'banana':
case 'strawberry':
alert("This is "+selectedValue+" and "+radioValue+". Do some conditional logic with the values!");
break;
default:
break;
}
}
}
This binds a function to change events on the radio buttons and the select and then uses a switch on the different values to do whatever you want it to do.
Updated:
I made another example, with checkboxes and the bool value from the checkboxes if they are selected
https://jsfiddle.net/75uLereo/2/

When "check-all" box checked, check others

I have a form located on my html page with a bunch of checkboxes as options. One of the options is "check-all" and I want all the other check boxes to be checked, if unchecked, as soon as the "check-all" box is checked. My code looks something like this:
<form method = "post" class = "notification-options">
<input type = "checkbox" name = "notification-option" id = "all-post" onClick = "javascript:checkALL(this
);"> All Posts <br/>
<input type = "checkbox" name = "notification-option" id = "others-post"> Other's Posts <br/>
<input type = "checkbox" name = "notification-option" id = "client-post"> Cilent's Post <br/>
<input type = "checkbox" name = "notification-option" id = "assign-post"> Task Assigned </form>
java script:
<script type = "text/javascript">
var $check-all = document.getElementbyId("all-post");
function checkALL($check-all){
if ($check-all.checked == true){
document.getElementByName("notification-option").checked = true;
}
}
</script>
nothing happens when I run my code
Here are some guidelines.
type attribute is not needed and can be omitted.
JS variable names can't contain hyphens, a typo in
getElementById()
You're using a global variable name as an argument, in the same time
you're passing this from online handler. The passed argument shadows the
global within the function.
if (checkAll.checked) does the job
Typo in getElementsByName(), gEBN() returns an HTMLCollection,
which is an array-like object. You've to iterate through the
collection, and set checked to every element separately.
Fixed code:
<script>
var checkAll = document.getElementById("all-post");
function checkALL(){
var n, checkboxes;
if (checkAll.checked){
checkboxes = document.getElementsByName("notification-option");
for (n = 0; n < checkboxes.length; n++) {
checkboxes[n].checked = true;
}
}
}
</script>
You can also omit the javascript: pseudo-protocol and the argument from online handler.
You can do it like this using jQuery:
$("#all-post").change(function(){
$('input:checkbox').not(this).prop('checked', this.checked);
});
Here is a JSfiddle
if all post check box is checked it will set check=true of others-post and client-post check boxes
$("input[id$=all-post]").click(function (e) {
if ($("input[id$=all-post]").is(':checked')) {
$("input[id$=others-post]").prop('checked', true);
$("input[id$=client-post]").prop('checked', true);
}
});
Check to see if any of the checkboxes are not checked first.
If so, then loop through them and check any that aren't.
Else, loop through them and uncheck any that are checked
I have an example at http://jsbin.com/witotibe/1/edit?html,output
http://jsfiddle.net/AX3Uj/
<form method="post" id="notification-options">
<input type="checkbox" name="notification-option" id="all-post"> All Posts<br>
<input type="checkbox" name="notification-option" id="others-post"> Other's Posts<br>
<input type="checkbox" name="notification-option" id="client-post"> Cilent's Post<br>
<input type="checkbox" name="notification-option" id="assign-post"> Task Assigned
</form>
function checkAll(ev) {
checkboxes = document.getElementById('notification-options').querySelectorAll("input[type='checkbox']");
if (ev.target.checked === true) {
for (var i = 0; i < checkboxes.length; ++i) {
checkboxes[i].checked = true;
}
} else {
for (var i = 0; i < checkboxes.length; ++i) {
checkboxes[i].checked = false;
}
}
}

How can I select all checkboxes from a form using pure JavaScript (without JS frameworks)?

I have question, how write function to select all chceckbox on form, when all checkbox Id start from some const. string, using pure java script
(without jquery and other frameworks) ? I know how do it using each function from JQuery, but I dont have any idea hwo do it in pure JS.My form ex.
<form id="myId" name="myForm">
<input type="checkbox" id="lang_1" value="de"/> DE
<input type="checkbox" id="lang_2" value="us"/> US
<input type="checkbox" id="lang_3" value="ru"/> RU
<input type="button" onclick="Select();" value="Select all"/>
</form>
You could use getElementsByTagName to get all the input elements:
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == "checkbox") {
inputs[i].checked = true;
}
}
Here's an example of that. If you only care about newer browsers, you could use querySelectorAll:
var inputs = document.querySelectorAll("input[type='checkbox']");
for(var i = 0; i < inputs.length; i++) {
inputs[i].checked = true;
}
And an example of that one. As an aside, you mentioned in your question that when using jQuery you could do this using each. You don't need to use each, as most jQuery methods operate on all elements in the matched set, so you can do it in just one line:
$("input[type='checkbox']").prop("checked", true);
In your case:
for (i = 1; i<3; i++) {
document.getElementById('lang_'+i).checked = true;
}

Categories