Select all checkbox functionality in classic asp - javascript

I have a select all checkbox followed by individual checkboxes corresponding to each record which comes from database.
How do I implement a javascript function such that when a person checks Select all,all the checkboxes get selected and vice versa.

first give an id to your select all check box say "selectall" and give a class to all other check boxes as allcheck and try using this code .
$("#selectall").click(function() {
if (!$(this).is(':checked'))
{
$('.allcheck').each(function(){
$(this).prop("checked", false);
});
}
else
{
$('.allcheck').each(function(){
$(this).prop("checked", true);
});
}
});
When user unchecks the box all should be unchecked , I guess that is also an expected functionality
NOTE : - I have given this answer assuming that you are using jquery

Try this:
function checkAll(id) {
var checkboxCollection = document.getElementById('<%= chkint.ClientID %>').getElementsByTagName('input');
for (var i = 0; i < checkboxCollection.length; i++) {
if (checkboxCollection[i].type.toString().toLowerCase() == "checkbox") {
checkboxCollection[i].checked = id.checked;
}
}
}
function select() {
var count = 0;
var chkSelectAll = document.getElementById('<%= selectall.ClientID %>');
var chkList = document.getElementById('<%= chkint.ClientID %>').getElementsByTagName("input");
for (var i = 0; i < chkList.length; i++) {
if (chkList[i].checked == true) {
count++;
}
}
if (count == chkList.length)
chkSelectAll.checked = true;
else
chkSelectAll.checked = false;
}
In this code, chkint is the ID of Checkboxlist and selectall is the ID of selectall checkbox.

Similar to Aravind, using jQuery you could group all your checkboxes in a container and give it an ID and give your SelectAll checkbox an ID. After that code is simple, see alse here for fiddle:
$("#selectall").click(function() {
if ($(this).is(':checked'))
$("#selectallcontainer :checkbox").not(this).attr('checked', true);
else
$("#selectallcontainer :checkbox").not(this).attr('checked', false);
});​

Here is a pure javascript solution:
jsFiddle here.
Simply attach the function to the onClick event of your 'Select All' checkbox and wrap the rest of your options in a div like so:
<script>
function checkAll() {
var checkbox_options = document.getElementById("checkbox_options");
var checkbox_all = document.getElementById("checkbox_all");
var checkboxes = checkbox_options.getElementsByTagName("input");
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = checkbox_all.checked;
}
}
</script>
<label><input id="checkbox_all" type="checkbox" onclick="checkAll()" />Select All</label><br />
<div id="checkbox_options">
<label><input type="checkbox" />CheckBox1</label><br />
<label><input type="checkbox" />CheckBox2</label><br />
<label><input type="checkbox" />CheckBox3</label><br />
</div>

Related

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

Apply function when any checkboxes are changed

I have an HTML form with checkboxes like so:
<form id="filterOptions" method="post" action="">
<input type="checkbox" name="filterTaxi" id="filterTaxi" />
<input type="checkbox" name="filterBicycle" id="filterBicycle" />
<input type="checkbox" name="filterCarPark" id="filterCarPark" />
<input type="checkbox" name="filterBed" id="filterBed" />
</form>
Now I want to use javascript to apply a function whenever a checkbox is changed.
At the moment I can apply a function when the first checkbox is changed like so:
document.getElementById('filterTaxi').onchange = function(){
//do something here
};
So my question is, how do I avoid writing that for every checkbox and instead have a function fired when any of the checkboxes are changed?
You can either select all input or add a class and do:
var input = document.getElementsByTagName('input');
for(var i = 0; i < input.length; i++) {
input[i].onchange = function() {
console.log(this);
}
}
onchange function can be the same for all of them.
fiddle: http://jsfiddle.net/XgS9K/
for all elements.
document.getElementById('filterOptions').onchange = function(){
alert()
};
This will give you the onchange handler for checking and unchecking of checkboxes.
var allInputs = document.getElementsByTagName('input');
for (var i = 0; i < allInputs.length; i++) {
if (allInputs[i].type == 'checkbox') {
allInputs[i].onchange = function () {
if (this.checked) {
// your checked code here
console.log('checked');
} else {
// your unchecked code here
console.log('unchecked');
}
}
}
}
DEMO http://jsfiddle.net/L324t/

Uncheck a checkbox if another checked with javascript

I have two checkbox fields. Using Javascript, I would like to make sure only one checkbox can be ticked. (e.g if one checkbox1 is ticked, if checkbox2 is ticked, checkbox1 will untick)
<input name="fries" type="checkbox" disabled="disabled" id="opt1"/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled"/>
I would also like to have a radio button beneath, if this is clicked, I would like both checkboxes to be unticked.
<input type="radio" name="o1" id="hotdog" onchange="setFries();"/>
Would the best way to do this be by writing a function, or could I use onclick statements?
Well you should use radio buttons, but some people like the look of checkboxes, so this should take care of it. I've added a common class to your inputs:
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
Demo: http://jsfiddle.net/5uUjj/
Also based on tymeJV's answer above, if you want to only deactivate the other checkbox when one is clicked you can do this:
function cbChange(obj) {
var instate=(obj.checked);
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
if(instate)obj.checked = true;
}
tymeJV's function does not let you have both unticked - this does.
(yes, weird but true.. sometimes there's a semantic reason why you want two tickboxes not radio buttons)
Hope this helps:
function setFries(){
var hotdog= document.getElementById("hotdog");
var opt1= document.getElementById("opt1");
var opt2 = document.getElementById("opt2");
if(hotdog.checked){
opt1.checked = false;
opt2.checked = false;
}else if(opt1.checked){
opt2.checked = false;
}else if(opt2.checked){
opt1.checked = false;
}
}
<input type="checkbox" name="fries" id="opt1" disabled="disabled" onclick="setFries(this);/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled" onclick="setFries(this);/>
<input type="radio" name="o1" id="hotdog" onclick="setFries(this);"/>
Note that I am using onclick event:
function setFries(obj){
var fries = document.getElementsByName('fries');
if(obj.id =='hotdog') //Or check for obj.type == 'radio'
{
for(var i=0; i<fries.length; i++)
fries[i].checked = true;
}
else{
for(var i=0; i<fries.length; i++){
if(fries[i].id != obj.id){
fries[i].checked = !obj.checked;
break;
}
}
}
}
The simplest way I found for this was to not use any sort of code at all. I triggered an actions in the check box properties.
1. mouse up to reset a form. I then unselected (for reset) all of my fields accept for my desired check boxes. I then did the same thing for my other check box to go the other way. You can basically turn the check boxes into toggles or have any sort of crazy pattern you want.

jquery enable disable link based on checkbox

I need to disable/enable "a.href" links based on checkboxes being checked. I have a list of checkboxes (2 columns). When at least one checkbox in a column "install" is checked, "Install" link should be enabled, otherwise disabled. When at least one checkbox is checked in column "Remove", a link with the same class name should be enabled, otherwise disabled.
I've tried with this but not sure if this is correct, it doesn't work:
function refleshCheckboxes() {
if ($("input:checked").length > 0) {
$("input:checked").each(function(index, e) {
var css = $(e).attr('class').split(' ').slice(-1);
$("div.markActions a").each(function (index, e) {
$(e).removeClass("disablelink").hasClass(css);
});
});
}
else {
$("div.markActions a").addClass("disablelink");
}
}
$("div.markActions a")
- this is where a.href links are (inside this div)
checkboxes have the same class name as the a.href links. So I would like to get the class name of checkbox and match that class with the class of the a.href link.
Checkbox:
<input type="checkbox" value="2" class="checkbox install">
Link:
<a class="iconDiskPlus install disablelink" href="#">Install</a>
I figured it out:
function refleshCheckboxes() {
if ($("input.checkbox:checked").length > 0) {
var arr = new Array(".install", ".uninstalled", ".enabled", ".disabled", ".download", ".remove");
for (i = 0; i < arr.length; i++) {
if ($("input.checkbox:checked").is(arr[i])) {
$(".markActions a" + arr[i]).removeClass("disablelink");
} else {
$(".markActions a" + arr[i]).addClass("disablelink");
}
};
}
else {
$("div.markActions a").addClass("disablelink");
}
}
Try the below one.
​
$(function(){
$('input.install').click(function(){
var install_link = $('a.install');
if($('input.install:checked').length !=0){
install_link.addClass('enablelink').text('install enabled');
}
else{
install_link.addClass('disablelink').text('install disabled');
}
});
});​
Check out js fiddle for demo
You can set an onclick event to a checkbox like this:
<input id="someId" type="checkbox" value="2" class="checkbox install" onclick="myFunction()">
in your js file define a function:
function myFunction(){
var checkBox = document.getElementById("someId");
if(checkBox.checked == true){
//you have to give an id attribute to the object
// which you want to hide
var hideIt = document.getElementById("id");
hideIt.style.visibility = "none";
}
}

How to hide the parent of an unchecked checkbox?

I have a set of random/dynamic generated div checkboxes:
<div>A1 <input type='checkbox' name='A[]' value='A1'> </div>
<div>A2 <input type='checkbox' name='A[]' value='A2'> </div>
<div>A3 <input type='checkbox' name='A[]' value='A3'> </div>
<div>B1 <input type='checkbox' name='B[]' value='B1'> </div>
<div>B2 <input type='checkbox' name='B[]' value='B2'> </div>
<div>C1 <input type='checkbox' name='C[]' value='C1'> </div>
What I am trying to do is when the user:
checks any A then the others will hide (entire div) but all A will still show.
unchecks a checkbox, then all A, B, C will show again.
This is because I am preventing the user from checking a mix of options.
PS:
You can provide a solution that might need me to modify the generated output of checkboxes.
try this fiddle
$("input[type=checkbox]").on("change", function() {
var thisName = $(this).attr("name");
if($(this).is(':checked')){
$(':checkbox').parent().hide();
$('input:checkbox[name|="'+thisName+'"]').parent().show();
} else {
$(':checkbox').parent().show();
}
});​
Try this one,
$('input:checkbox').click(function(){
if($(this).attr('checked') == 'checked'){
$('input:checkbox').parent('div').hide();
$('input:checkbox[name="'+$(this).attr('name')+'"]').parent('div').show();
}else{
if(!$('input:checkbox[checked="checked"]').length){
$('input:checkbox').parent('div').show();
}
}
})
​
Demo: http://jsfiddle.net/muthkum/uRd3e/3/
You can use some JQuery traversing to hide the non-matching elements:
// add the event handler
$("input[type=checkbox]").on("change", function() {
// get whether checked or unchecked
var checked = $(this).prop("checked") === true;
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the grandparent element
$(this).parent().parent()
// get all the checkboxes
.find("input[type=checkbox]")
// filter to only the ones that don't match the current name
.filter(function(i, e) { return e.name != thisName; })
// hide or display them
.css("display", checked ? "none" : "");
});
you can simple do it like this
$('input[type=checkbox]').change(function () {
if ($(this).attr('checked')) {
var Name = $(this).prop("name");
$('div').filter(function(){
return $(this).find('input[type=checkbox]').prop("name") != Name;
}).hide();
}
else
{
$('input[type=checkbox]').attr('checked',false);
$('input[type=checkbox]').parent('div').show();
}
});​
Live Demo
Try code bellow:
$(":checkbox").click(function() {
var identifier = $(this).val().substring(0, 1);
$("input[type='checkbox']").each(function() {
if ($(this).val().indexOf(identifier) != -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
if ($("input:checked").length == 0) {
$("input[type='checkbox']").parent().show();
}
});
You can try on jsFiddle
This will hide all other checkbox types when FIRST of a type is checked and show all the other checkbox types when ALL of the checked box type are unchecked:
$("input:checkbox").on("change", function() {
// get the name attribute
var nameAttr = $(this).prop("name");
// check how many checkbox inputs of that name attribute are checked
var checkedLength = $("input:checkbox[name=\"" + nameAttr + "\"]:checked").length;
// if 0, display other checkbox inputs, else if 1 hide all of the rest
if(checkedLength == 0) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().show();
}else if(checkedLength == 1) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().hide();
}
});
Overwhelmed by choice! Here's a plain JS version that just disables members of the non–selected groups.
I think that's better than hiding them so users can see the other options after they've selected one. Otherwise, to see the other options again, they must deselect all checkboxes in the group.
Note that div is a parent of the inputs, the listener passes a reference to the element and the related event object, modify as required.
<script>
function doStuff(div, evt) {
var checked, el, group, j, inputs, name, re;
var t = evt.target || evt.srcElement;
if (t.nodeName && t.nodeName.toLowerCase() == 'input' && t.type == 'checkbox') {
inputs = div.getElementsByTagName('input');
name = t.name;
// Set checked to true if any input with this name is checked
group = document.getElementsByName(name);
j = group.length;
while (j-- && !checked) {
checked = group[j].checked;
}
// Loop over inputs, hide or show depending on tests
for (var i=0, iLen=inputs.length; i<iLen; i++) {
el = inputs[i];
// If name doesn't match, disable
el.disabled = checked? (el.name != name) : false;
}
}
}
</script>
<div onclick="doStuff(this, event)">
<div>A1 <input type='checkbox' name='A[]' value='A1'></div>
<div>A2 <input type='checkbox' name='A[]' value='A2'></div>
<div>A3 <input type='checkbox' name='A[]' value='A3'></div>
<div>B1 <input type='checkbox' name='B[]' value='B1'></div>
<div>B2 <input type='checkbox' name='B[]' value='B2'></div>
<div>C1 <input type='checkbox' name='C[]' value='C1'></div>
</div>
Thanks guys, especially dbaseman (get me ideal) :
ok, Here is my code after referring from you all.
$("input[type=checkbox]").on("click", function() {
var sta = $(this).is(":checked"); sta=(sta==true?1:0);
if(sta==1){
var thisName = $(this).prop("name"); thisName=thisName.replace("[]","");
$("div input[type=checkbox]:not([name^=" + thisName + "])").parent().hide();
}else{
var num = $("[type=checkbox]:checked").length;
if(num==0){
$("div input[type=checkbox]").parent().show();
}
}
});
so far code able is performing as what i need.
Ps: i am still weak on jquery travelling part
Ps: Edited on re-opening all checkboxes part
Thanks once again!

Categories

Resources