Unchecking all checkboxes with the escape key - javascript

I'm trying to enable the user to uncheck all checkboxes with the escape key.
I found this code snippet that does the job, but by clicking a button.
<form>
<input type="checkbox" name="checkBox" >one<br>
<input type="checkbox" name="checkBox" >two<br>
<input type="checkbox" name="checkBox" >three<br>
<input type="checkbox" name="checkBox" >four<br>
<input type=button name="CheckAll" value="Select_All" onClick="check(true,10)">
<input type=button name="UnCheckAll" value="UnCheck All Boxes" onClick="check(false,10)">
</form>
function check(checked,total_boxes){
for ( i=0 ; i < total_boxes ; i++ ){
if (checked){
document.forms[0].checkBox[i].checked=true;
}else{
document.forms[0].checkBox[i].checked=false;
}
}
}
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
// uncheck all checkboxes
}
});
The code doesn't work on checkboxes that are not in a tag.
Sometimes I use checkboxes for CSS only on-click events, which are not inside of a form.
The use case here is for CSS only menu pop-ups and drop-downs.
I'm trying to make them accessible by allowing the user to close with the escape key.
Sure, it's not CSS only any more, but I need to improve accessibility.

This should do it:
function allCB(checked){
document.querySelectorAll("input[type=checkbox]").forEach(cb=>cb.checked=checked)
}
document.addEventListener('keydown',_=>event.key === 'Escape' && allCB(false));
document.querySelector("form").addEventListener('click',ev=>ev.target.type=="button" && allCB(ev.target.name=="CheckAll"));
<form>
<label><input type="checkbox" name="checkBox">one</label><br>
<label><input type="checkbox" name="checkBox">two</label><br>
<label><input type="checkbox" name="checkBox">three</label><br>
<label><input type="checkbox" name="checkBox">four</label><br>
<input type=button name="CheckAll" value="Select_All">
<input type=button name="UnCheckAll" value="UnCheck All Boxes">
</form>

Related

Radio button value selector

I am trying to write a form. In the form there will be one set of radio buttons. When I open my html page on my browser, I would like to click one of the buttons and then write its value in a text after I click a submit button.
This is part of the form code:
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd><input type="radio" checked="checked" name="tb" value="1"/>
block
<input type="radio" name="tb" value="2" />
dark
<input type="radio" name="tb" value="3" />
f1b
<input type="radio" name="tb" value="0" />
custom
<p></p>
</dl>
</form>
And this is part of my javascript code:
function buildData(){
var txt =
"type = " + ($("[name='tb']").is(":checked") ? "block" :
($("[name='tb']").is(":checked") ? "dark" :
($("[name='tb']").is(":checked") ? "f1b" : "custom")))
return txtData;
}
$(function(){
// This will act when the submit BUTTON is clicked
$("#formToSave").submit(function(event){
event.preventDefault();
var txtData = buildData();
window.location.href="data:application/octet-stream;base64,"+Base64.encode(txtData);
});
});
But it is currently not working properly (it won't save the right selection in txt).
How can I fix it? Thanks in advance
UPDATE:
From one of the answers:
function buildData(){
var txtData =
"some text... " + $("[name=tipoBooster]").change(function() {
var txt = ["custom","block","dark","f1b"][this.value];
console.log(txt);
}) + "other text...";
return txtData;
}
Here is a simple solution for getting user input when the user changes the checked radio button
$("[name=tb]").change(function() {
var txt = ["custom","block","dark","f1b"][this.value];
console.log(txt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd><input type="radio" checked="checked" name="tb" value="1"/>
block
<input type="radio" name="tb" value="2" />
dark
<input type="radio" name="tb" value="3" />
f1b
<input type="radio" name="tb" value="0" />
custom
<p></p>
</dl>
</form>
but in your case you need to edit the build function to be like this
function buildData(){
return "type = " + ["custom","block","dark","f1b"][$("[name='tb']:checked").val()];
}
Or if you want more flexible solution you can add labels to your inputs
like this
$("[name='tb']").change(function() {
console.log($(this).parent().text().trim());
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd>
<label><input type="radio" name="tb" value="1" checked="checked" />block</label>
<label><input type="radio" name="tb" value="2" />dark</label>
<label><input type="radio" name="tb" value="3" />f1b</label>
<label><input type="radio" name="tb" value="0" />custom</label>
</dd>
<p></p>
</dl>
</form>
this was for a change event but your build function should be like this then
function buildData() {
return $("[name='tb']:checked").parent().text().trim();
}
Explanation:
$("[name='tb']:checked") gets the checked radio input element
.parent() gets its parent since we need the label to get its text
.text() gets the text of the label
.trim() removes white space before and after the text
Your selector is referencing an id not the name attribute. Try this instead.
var txt =
"type = " + ($("[name='tb']").is(":checked") ? "block" :
($("[name='tb']").is(":checked") ? "dark" :
($("[name='tb']").is(":checked") ? "f1b" : "custom")))
You could use: $("[name='tb']").val() and just set the corresponding values on the actual radio buttons to block dark etc.
e.g:
<input type="radio" checked="checked" name="tb" value="block"/>
block
<input type="radio" name="tb" value="dark" />
dark
<input type="radio" name="tb" value="f1b" />
f1b
<input type="radio" name="tb" value="custom" />
custom
A # in a jQuery selector is for selecting by id attribute.
What if you change the selector from ($("#tb").is(":checked")... to a name selector.
e.g.
($("input[name*='tb']").is(":checked")
If you just want to get the selected radio button's text. Could you update the html to be.
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd>
<input id="option1" type="radio" checked="checked" name="tb" value="1"/>
<label for="option1">block</label>
...
<p></p>
</dl>
</form>
Then your function can just return the selected text
function buildData(){
return "type = " + $("input[name*='tb']").is(":checked").next("label").text();
}
If you don't want to add labels to the html, then I would try $("input[name*='tb']").is(":checked").next().text();
Maybe sharing a minimum working example link would help, as I am just writing the above from memmory, referencing the documentation (https://api.jquery.com/text/#text).

select only one checkbox in a group not working 100%

I'm trying to make it where the user can only select 1 checkbox at a time on a page.
Here's my code so far:
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('active', 'inactive',
'showall')
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false
})
}
<strong>Active</strong>
<input type="checkbox" name="active" value="Yes" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="inactive" value="Yes" onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="showall" value="Yes" onclick="onlyOne(this)">
What keeps happening is it will work sometimes and sometimes they can select more than 1 checkbox. What do I need to tweak to get it working all the time.
HTML DOM getElementsByName() Method Gets all elements with the specified name
So In your code It's getting only the first name active ;
as a result the length of the list of checkboxs is 1 this is why your code doesn't work correctly.
If you want to make sure that what i am saying is true change your code to this and your logic will work just fine:
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('active');
checkboxes.forEach((item) => {
if (item !== checkbox)
item.checked = false;
})
}
<strong>Active</strong>
<input type="checkbox" name="active" value="Yes" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="active" value="Yes"
onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="active" value="Yes" onclick="onlyOne(this)">
As the others recommended use the radio buttons it's much easier I just wanted to clear this for you.
EDIT :
If you still want to use checkbox use querySelectorAll instead of your getElementsByName
var checkboxes = document.querySelectorAll('[name="active"], [name="inactive"], [name="showall"]');
You can use radio buttons to do this, it needs no JavaScript and is supported by pretty much everything, Internet Explorer included. They can be used like so:
<div>
<strong>Active</strong>
<input type="radio" name="select" id="active" checked> <!-- Checked means that it is initially selected -->
</div>
<div>
<strong>Inactive</strong>
<input type="radio" name="select" id="inactive">
</div>
<div>
<strong>Show All</strong>
<input type="radio" name="select" id="showall">
</div>
Notice how because they are all technically the same input, they all have to have the same name, but you can instead use IDs to tell between them if you really need to.
Using radio buttons would be the preferred choice. But if you do want to use checkboxes, you can use the following approach.
<strong>Active</strong>
<input type="checkbox" name="chkbox" value="Yes" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="chkbox" value="Yes"
onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="chkbox" value="Yes" onclick="onlyOne(this)">
<script>
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('chkbox')
checkboxes.forEach((item) => {
item.checked = false
})
checkbox.checked = true
}
</script>
Note that the name attribute for all the input fields are the same.
getElementsByName() only takes one argument. The other arguments you're giving are being ignores, so you're only processing the active checkbox.
Give all your checkboxes the same class, and use getElementsByClassName() instead.
function onlyOne(checkbox) {
var checkboxes = Array.from(document.getElementsByClassName('radio'))
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false
})
}
<strong>Active</strong>
<input type="checkbox" name="active" value="Yes" class="radio" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="inactive" value="Yes" class="radio" onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="showall" value="Yes" class="radio" onclick="onlyOne(this)">
You are using getElementsByName incorrectly as you can only pass one name to it and it is not an Array so you can't forEach it.
You can use querySelectorAll to query by multiple names and use forEach from the Array prototype.
function onlyOne(checkbox) {
var checkboxes = document.querySelectorAll('[name=active],[name=inactive],[name=showall]')
Array.prototype.forEach.call(checkboxes, (item,i) => {
if (item !== checkbox) item.checked = false
})
}
<strong>Active</strong>
<input type="checkbox" name="active" value="Yes" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="inactive" value="Yes"
onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="showall" value="Yes" onclick="onlyOne(this)">
While using a radio button control might be the way to go, that just really a comment and not an answer.

Javascript - unselect checkboxes, items mutually exclusive

I have a group of check boxes that are all part of one array. What I require is that if the first one is selected (I don't mind), then any of the others are unselected, and vice versa - if one of the bottom three options are selected, then I don't mind needs to be unselected.
The last three options can all be selected at the same time.
This Link is similar to what I am asking to do. Any help would be appreciated
<fieldset class="checkbox">
<legend>Sitter type</legend>
<div id="field_844" class="input-options checkbox-options">
<label for="field_1071_0" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1071_0" value="I don't mind">I don't mind</label>
<label for="field_1072_1" class="option-label">
<input checked="checked" type="checkbox" name="field_844[]" id="field_1072_1" value="Sitter">Sitter</label>
<label for="field_1073_2" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1073_2" value="Nanny">Nanny</label>
<label for="field_1074_3" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1074_3" value="Au Pair">Au Pair</label>
</div>
</fieldset>
The code is exactly the same as the link you provided.
<fieldset class="checkbox">
<legend>Sitter type</legend>
<div id="field_844" class="input-options checkbox-options">
<label for="field_1071_0" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1071_0" value="I don't mind">I don't mind</label>
<label for="field_1072_1" class="option-label">
<input checked="checked" type="checkbox" name="field_844[]" id="field_1072_1" value="Sitter">Sitter</label>
<label for="field_1073_2" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1073_2" value="Nanny">Nanny</label>
<label for="field_1074_3" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1074_3" value="Au Pair">Au Pair</label>
</div>
</fieldset>
And then:
// We cache all the inputs except `#field_1071_0` with `:not` pseudo-class
var $target = $('input:not(#field_1071_0)');
$('#field_1071_0').on('change', function () {
// if 'i don't mind' is selected.
if (this.checked) {
// remove the 'checked' attribute from the rest checkbox inputs.
$target.prop('checked', false);
}
});
$target.on('change', function () {
// if one of the bottom three options are selected
if (this.checked) {
// then I don't mind needs to be unselected
$('#field_1071_0').prop('checked', false);
}
});
Demo: https://jsfiddle.net/426qLkrn/4/
I cannot remember an in-house feature of JavaScript or jQuery that makes it possible to solve your problem. So, you have to solve it by your own.
You can add a data attribute to your checkboxes where you list all the checkboxes (as an id) which cannot be selected at the same time with the current checkbox, e.g.:
<input type="checkbox" name="field_844[]" id="field_1071_0" value="I don't mind" data-exclude="['field_1072_1','field_1072_2','field_1072_3']" />
<input checked="checked" type="checkbox" name="field_844[]" id="field_1072_1" value="Sitter" data-exclude="['field_1071_0']" />
...
Then, you add, for example, an onchange event to each of the checkboxes. This event checks whether the checkbox has changed to checked or to unchecked. If it has changed to checked, you have to uncheck all checkboxes within the list:
document.getElementById("field_1071_0").onchange= function(e) {
if (this.checked) {
this.dataset.exclude.forEach(function (exc) {
document.getElementById(exc).checked = false;
});
}
};
Or, with jQuery:
$("#field_1071_0").change(function (e) {
if ($(this).prop("checked")) {
$(this).data('exclude').forEach(function (exc) {
$("#" + exc).prop("checked", false);
});
}
});
The good thing is: You can apply this function to each checkbox you want, e.g.:
$("input:checkbox").change(function (e) {
if ($(this).prop("checked")) {
$(this).data('exclude').forEach(function (exc) {
$("#" + exc).prop("checked", false);
});
}
});
Now, each checkbox has the desired behaviour. So, this solution is a general way to solve it.
Comment: If you do not have access to the HTML code, i.e., to the input fields to add some information like the data-attribute, you can add those information via jQuery/JavaScript too:
$("#field_1071_0").data("exclude", ['field_1072_1','field_1072_2','field_1072_3']);
$("#field_1072_1").data("exclude", ['field_1071_0']);
...
jquery prop method can be used to pragmatically check or unchecked a check box. is can be use to evaluate if a condition is true or false.
Hope this snippet will be useful
// if first check box is selected , then checkedremaining three
$("#field_1071_0").on('change', function() {
//$(this) is the check box with id field_1071_0
// checking if first checkbox is checked
if ($(this).is(":checked")) {
//opt2 is a common class for rest of the check boxes
// it will uncheck all other checkbox
$(".opt2").prop('checked', false)
}
})
//unchecking first checkbox when any of the rest check box is checked
$(".opt2").on('change', function() {
if ($(this).is(":checked")) {
$("#field_1071_0").prop('checked', false)
}
})
<!--Adding a class `opt2` to the last three checkboxes-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="checkbox">
<legend>Sitter type</legend>
<div id="field_844" class="input-options checkbox-options">
<label for="field_1071_0" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1071_0" value="I don't mind">I don't mind</label>
<label for="field_1072_1" class="option-label">
<input checked="checked" type="checkbox" class="opt2" name="field_844[]" id="field_1072_1" value="Sitter">Sitter</label>
<label for="field_1073_2" class="option-label">
<input type="checkbox" name="field_844[]" class="opt2" id="field_1073_2" value="Nanny">Nanny</label>
<label for="field_1074_3" class="option-label">
<input type="checkbox" name="field_844[]" id="field_1074_3" value="Au Pair" class="opt2">Au Pair</label>
</div>
</fieldset>

Checkbox to toggle all selection

I have this javascript code
// Listen for click on toggle checkbox
$('#select-all').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
});
}
});
And I have this
<form action="" method="POST">
Toggle All :
<input type="checkbox" name="select-all" id="select-all" />
then at my table I have multiple checkbox
<input type="checkbox" name="checkbox-1" id="checkbox-1" value="1"> Select
<input type="checkbox" name="checkbox-2" id="checkbox-2" value="2"> Select
<input type="checkbox" name="checkbox-3" id="checkbox-3" value="3"> Select
<input type="checkbox" name="checkbox-4" id="checkbox-4" value="4"> Select
When I click on toggle all, it does not check checkbox-1 to checkbox-4
What went wrong in my javascript code.
Thanks!! I want to actually do a function that will send all the value of checkbox1-4 by post when they are checked on form submit.
Simply do like this.
$('#select-all').click(function(event) {
$(':checkbox').prop("checked", this.checked);
});
You do not need to loop through each checkbox to check all.
Demo
Wrap the code in dom ready if your script is in head tag
$(document).ready(function() {
$('#select-all').click(function(event) {
$(':checkbox').prop("checked", this.checked);
});
});

How to replace a p tag value if a radio is checked?

I want replace a p tag value if a radio is checked.
I write some JS to do this,but nothing changed.
this is my code(I use jquery)
<script>
$(function(){
if ($('#A:checked')) {
$("#change_me").html('<input type="radio" value="1" name="fruit">')
}
if ($('#B:checked')) {
$("#change_me").html('<input type="radio" value="2" name="fruit">')
}
}
</script>
<input type="radio" name="e" id="A" checked="checked">
<input type="radio" name="e" id="B">
<p id="change_me">
<input type="radio" value="1" name="fruit">
</p>
Thanks.
The :checked selector matches elements that are currently checked.
Writing $('#B:checked') returns a jQuery object containing either zero or one element. It cannot be used directly as a condition.
Instead, you can check if ($('#B:checked').length) to see whether the jQuery object has anything in it.
First, you don't need to recreate the radio button if only the value is changing.
$(function(){
if ($('#A:checked').size() > 0) {
$("#change_me input[type=radio]").val('1')
}
if ($('#B:checked').size() > 0) {
$("#change_me input[type=radio]").val('2')
}
}
HTML:
<input type="radio" name="e" id="A" checked="checked">
<input type="radio" name="e" id="B">
<p id="change_me">
<input type="radio" value="1" name="fruit">
</p>
Replace the JavaScript code you have with the following
$(function(){
$('input[name=e]').change(function(){
if($(this).attr('id') == 'A')
{
$("#change_me input").val('1');
}
else
{
$("#change_me input").val('2');
}
});
});

Categories