Apply function when any checkboxes are changed - javascript

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/

Related

JS: uncheck box when another is checked but also uncheck itself if checked

I have three checkboxes. I am already using a piece of code I found here to uncheck the other two when one is checked.
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
I use this inside the checkbox to toggle the state: onchange="cbChange(this)".
However, I also need to provide for a situation where I don't want any of the boxes ticked. While I can do this by adding a separate button or checkbox, I wanted to know if the above code can be modified or another function added that will allow to untick the already ticked box by an onclick event.
I tried adding this function (again found here) but it won't work:
function cbUncheck(obj)
{
if (obj.checked == false)
{
document.getElementByClassName("cb").checked = false;
}
}
I use this in the checkbox code: onclick="cbUncheck(this);"
Suggestions welcome!
Thanks!
you need to check first checkbox checked or not..
if checkbox is not checked then dont need to do anything
otherwise uncheck other checkboxes
<input id="chk1" class="cb" type="checkbox" value="01" onchange='cbChange(this)' />
<label for="chk1" >1</label>
<input id="chk2" class="cb" type="checkbox" value="01" onchange='cbChange(this)' />
<label for="chk2" >1</label>
<input id="chk3" class="cb" type="checkbox" value="01" onchange='cbChange(this)' />
<label for="chk3" >1</label>
javascript
function cbChange(obj) {
if(obj.checked)
{
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
}
JS BIN JSBIN EXAMPLE
You can use radio buttons so that only one can be selected (no script required for that). Then if some other condition occurs, clear both (below uses a button as an example):
<form>
<input type="radio" name="foo" value="0">zero<br>
<input type="radio" name="foo" value="1">one<br>
<button type="button" onclick="clearRadios(this.form.foo)">Clear radios</button>
</form>
And the function:
function clearRadios(radioGroup) {
for (var i=0; i<radioGroup.length; i++) {
radioGroup[i].checked = false;
}
}
If you don't want users to check the radios at all, disable them.
This below code simply give solutions to what you need.
this.scan=function(index)
{
if( this.boxGroup[ index ].checked )
for(var i=0, g=this.boxGroup, len=g.length; i<len; i++)
if( i != index )
g[i].checked = false;
}
for working demo see jsfiddle

Hiding multiple form fields using checkboxes

I have this code that I need to edit so I can use it on multiple chkBox's and txtBox's.
Currently I can only hide one input field with one check box.
I know HTML and CSS but I am not familiar with JS.
I would like to be able to add a number at the end of each ID.
chkBox1, chkBox2, chkBox3... txtBox1, txtBox2, txtBox3...
Do I need to change getElementById to getElementsByTagName()?
JSFIDDLE for some reason it does not work here...?
This is my current code which hide the text field unless the checkbox is checked:
function showHide(){
var chkBox = document.getElementById("chkBox");
var txtBox = document.getElementById("txtBox");
if (chkBox.checked){
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
}
The reason your code wasn't working is because it was running onLoad. Your DOM and the onclick were created before the load was complete. You could just move your code into your <head></head> tags and it will work as is. See here, all I did was select the "No wrap - in head", no code changes.
You could also continue to have your javascript run onLoad and remove your onclick and add an eventlistener in the javascript like this:
JSFiddle
var txtBox = document.getElementById("txtBox");
document.getElementById("chkBox").addEventListener("click", function() {
if (this.checked) {
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
});
If you have multiple instances of this, I would change your DOM a bit sort of like this:
<form>
<div class="option">
<input type="text" name="txtBox1" class="hiddenInput" />
<br/>
<input type="checkbox" name="chkBox1" id="chkBox1" class="showHideCheck" />
<label for="chkBox1">Click me to show the text box</label>
</div>
<div class="option">
<input type="text" name="txtBox2" class="hiddenInput" />
<br/>
<input type="checkbox" id="chkBox2" name="chkBox2" class="showHideCheck" />
<label for="chkBox2">Click me to show the text box</label>
</div>
</form>
and do your JQuery like this (since you previously tagged jquery):
$(".hiddenInput").hide();
$(".showHideCheck").on("change", function() {
$this = $(this);
$input = $this.parent().find(".hiddenInput");
if($this.is(":checked")) {
$input.show();
} else {
$input.hide();
}
});
JSFiddle
Or with pure javascript and the similar DOM as above:
var checkBoxes = document.getElementsByClassName("showHideCheck");
for (var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].addEventListener('click', function () {
var txtBox = getAssociatedTextBox(this);
if (this.checked) {
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
}, false);
}
function getAssociatedTextBox(ele) {
var childNodes = ele.parentNode.childNodes;
for (i = 0, j = childNodes.length; i < j; i++) {
if (childNodes[i].className == "hiddenInput") {
return childNodes[i];
}
}
}
JSFiddle
Try this,
Javascript
$(document).ready(function(){
$("input[type=checkbox]").change(function(){
var oTxt = $("#txtBox" + $(this).attr("id").replace("chkBox", ""));
if($(this).is("checked"))
oTxt.show()
else
oTxt.hide();
});
});
HTML
<input type="checkbox" id="chkBox1"/>
<input type="textbox" id="txtBox1"/>
<input type="checkbox" id="chkBox2"/>
<input type="textbox" id="txtBox2"/>

Select all checkbox functionality in classic asp

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>

too see if checkboxes have been checked javascript

Hallo
How would I go about in checking whether checkBox has been checked in javascript?
I C# it is simple enough
int selected = 0;
for (int loop = 0; loop < chkMeal.CheckedItems.Count; loop++)
{
selected++;
}
if (selected > 1)
{
MessageBox.Show("only one meal allowed", "Halt", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
How could I do a simlar thing with javascript?
kind regards
Arian
For instance, if you give your checkboxes a class you can do something like this:
var myboxes = document.getElementsByClassName('myboxes');
for (var i=0; i<myboxes.length;i++) {
if (myboxes[i].checked) {
alert('Box number '+i+' is checked!');
}
}
Simply put, give your form a unique id attribute. Then, traverse HTMLFormElement.elements and check against HTMLInputElement.checked for a truthy value.
HTML:
<form id="foo" method="post" action="./">
<input type="checkbox" name="check_a" value="foo" />
<input type="checkbox" name="check_b" value="bar" />
<input type="checkbox" name="check_c" value="baz" checked />
</form>
JS:
var foo = document.getElementById("foo"), i = 0, el;
for(i;i<foo.elements.length;i++)
{
el = foo.elements[i];
if(el.nodeType === 1 && el.tagName === "INPUT" && el.type === "checkbox")
{
//element node, is an input element, is a checkbox
if(el.checked)
{
//checkbox is checked
}
}
el = null;
}
Bonus reference:
HTMLFormElement (via DOM Level 2)
HTMLInputElement (via DOM Level 2)
Using a little bit of jQuery:
$(function() {
$('form').submit( function() {
if ($('[name="chkMeal"]:checked').length > 1) {
// show an error
return false; // cancel submit
}
});
});

Using JavaScript to manipulate HTML input (checkbox) elements via type instead of name

I am implementing an HTML form with some checkbox input elements, and I want to have a Select All or DeSelect All button. However, I do not want to rely on the name of the input element (like this example) but rather the type because I have multiple checkbox groups with different names. Is there a way to check and uncheck all checkbox input elements within a form with JavaScript by relying on the type instead of the name?
Edit: We rely on YUI libraries, so I have access YUI if that provides a solution.
This should do it:
<script>
function checkUncheck(form, setTo) {
var c = document.getElementById(form).getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
c[i].checked = setTo;
}
}
}
</script>
<form id='myForm'>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='button' onclick="checkUncheck('myForm', true);" value='Check'>
<input type='button' onclick="checkUncheck('myForm', false);" value='Uncheck'>
</form>
function findCheckBoxes(el, check) {
for(var i=0;el.childNodes[i];i++)
{
var child = el.childNodes[i];
if (child.type=="checkbox")
{
child.checked = check;
}
if (child.childNodes.length > 0)
this.findCheckBoxes(child, check);
}
}
iterate through the form.elements collection and check .type == "checkbox".
var button = getSelectAllButtonInFormSomeHow();
/*all formelements have a reference to the form. And the form has an elements-collection.*/
var elements = button.form.elements;
for(var i = 0; i < elements.length;i++) {
var input = elements[i];
if (input.tagName == "input" && input.type == "checkbox") input.checked = true;
}
Every input element has an attribute, type, which for checkboxes is "checkbox" so you could try something like this:
for (var i = 0; i < document.myForm.elements.length; i++) {
if (document.myForm.elements[i].type == "checkbox") {
document.myForm.elements[i].checked = true;
}
}
If jQuery is an option you can do this rather easily.
See the documentation on jQuery selectors. (The last example in the section shows how to do it with radio buttons but just replace that with check boxes.)
Is assigning a class to all required checkbox elements an option? If yes, then this is how I would do it (assuming "class_name" is the name of the css class present in all checkbox elements in question):
function selectCheckBoxes(bChecked) {
var aCheckBoxes = YAHOO.util.Dom.getElementsByClassName('class_name', 'input');
for (var i = 0; i < aCheckBoxes.length; i++) {
aCheckBoxes[i].checked = bChecked;
}
}
If you want to stay away from classes, but can get parent element by ID (or any other method, I will use ID in the example, though), than you can do this:
function selectCheckBoxes(bChecked) {
var oParent = document.getElementById('parentsID');
var aElements = oParent.getElementsByTagName('input');
for (var i = 0; i < aElements.length; i++) {
if (aElements[i].type == 'checkbox') {
aElements[i].checked = bChecked;
}
}
}
I would stick to the "class" method, however.
<html>
<head>
<script>
function selectCheckBox()
{
if(document.getElementById('id11').checked==true)
{
document.frm.id2.checked=true
document.frm.id3.checked=true
document.frm.id4.checked=true
}
if(document.getElementById('id11').checked==false)
{
document.frm.id2.checked=false
document.frm.id3.checked=false
document.frm.id4.checked=false
}
}
function selectCheckBox1()
{
if(document.getElementById('id12').checked==false)
{
document.frm.id1.checked=false
}
}
function selectCheckBox2()
{
if(document.getElementById('id13').checked==false)
{
document.frm.id1.checked=false
}
}
function selectCheckBox3()
{
if(document.getElementById('id14').checked==false)
{
document.frm.id1.checked=false
}
}
</script>
</head>
<body>
<form name="frm">
All :<input type="checkbox" id="id11" name="id1" value="1" onClick="selectCheckBox()"><br>
A. :<input type="checkbox" id="id12" name="id2" value="2" onClick="selectCheckBox1()"><br>
B. :<input type="checkbox" id="id13" name="id3" value="3" onClick="selectCheckBox2()"><br>
C. :<input type="checkbox" id="id14" name="id4" value="4" onClick="selectCheckBox3()"><br>
</form>
</body>
</html>

Categories

Resources