Display value of checked check boxes javascript - javascript

Here I have written a javascript which selects all checkboxes on checking one checkbox and I want to display all the checked checkboxes value on button click. here it does selectall function correctly(ie. it selects all checkboxes). I am new to javascript and I need some help to display all the checked check box values, can any any one provide me the code to select all checkbox by clicking on a check box and display values of only selected checkboxes in a single function using javascript only...
Here is the javascript code
<script>
var checked=false;
function checkedAll ()
{
var c = document.getElementsByName("viju");
checked = document.getElementById('causelist_month').checked;
for (var i =0; i < c.length; i++)
{
c[i].checked=checked;
}
}
</script>
Here the HTML code
<input type="checkbox" name="causelist_month" id="causelist_month" onclick="checkedAll ();">select all/unselect all
<input type="checkbox" name="viju" id="viju" value="Jan" onClick="">jan
<input type="checkbox" name="viju" id ="viju" value="feb" onClick="">feb
<input type="Button" value="Show values" onClick="checkedAll(this.value)"/>

Jsfiddle http://jsfiddle.net/2UFdc/
HTML
<form>
<input type="checkbox" name="causelist_month" id="causelist_month" onclick="checkedAll ();">select all/unselect all
<input type="checkbox" name="viju" id="viju" value="Jan" onClick="">jan
<input type="checkbox" name="viju" id ="viju" value="feb" onClick="">feb
<input type="Button" value="Show values" onClick="showVal(this.form)"/>
</form>
Javascript
var checked = false;
function checkedAll() {
var c = document.getElementsByName("viju");
checked = document.getElementById('causelist_month').checked;
for (var i = 0; i < c.length; i++) {
c[i].checked = checked;
}
}
function showVal(frm) {
var arr = [];
for (var i in frm.viju) {
if (frm.viju[i].checked) {
arr.push(frm.viju[i].value);
}
}
alert(arr);
return arr
}

First, use the event listener for the checkboxes rather than onClick:
document.getElementById("causelist_month").addEventListener('change', function(){
checkboxes = document.getElementsByName("viju");
for( var i=0; i<checkboxes.length; i++){
checkboxes[i].checked = this.checked;
}
}, false);
And for the display of the checked items, in HTML:
<input type="Button" value="Show values" onClick="displayChecked()"/>
<div id="display"></div>
Then, in javascript:
function displayChecked (){
var display = "";
checkboxes = document.getElementsByName("viju");
for( var i=0; i<checkboxes.length; i++){
if( checkboxes[i].checked ){
display += " " + checkboxes[i].value;
}
}
document.getElementById("display").innerHTML = display;
}

you could use jquery functions
dont forget to inclde jquery library
<button id="showall"> display </button>
`
$("#showall").click(function() {
var array = [];
$(':checkbox:checked').each(function(i){
array[i] = $(this).val();
});
$.each( array, function( i, val ) {
$("#display").append(val); //the div where you want to display
});
});
`

<!DOCTYPE html>
<html>
<script>
var checked=false;
function checkedAll()
{
var c = document.getElementsByName("viju");
var checkboxesChecked = [];
// loop over them all
for (var i=0; i<c.length; i++) {
// And stick the checked ones onto an array...
if (c[i].checked) {
checkboxesChecked.push(c[i]);
}
}
if(document.getElementById('causelist_month').checked)
{
checked = document.getElementById('causelist_month');
checkboxesChecked.push(checked);
}
for (var j=0; j<checkboxesChecked.length; j++) {
// iterate the pushed values
alert(checkboxesChecked[j].value);
}
}
</script>
<body>
<form>
<input type="checkbox" name="causelist_month" id="causelist_month" value="select all/unselect all" onclick="checkedAll ();">select all/unselect all
<input type="checkbox" name="viju" id="viju" value="Jan" onClick="">jan
<input type="checkbox" name="viju" id ="viju" value="feb" onClick="">feb
<input type="Button" value="Show values" onClick="checkedAll(this.value)"/>
<form>
</body>
</html>
This displays all the list of check boxes in the alert message one by one. please check

Related

Loop radio-button form javascript

I am trying to loop a radio-button form but with no success.
Despite the length of the form is 3 (same as number of radiobuttons) I can not access individual elements.
The purpose is to change the text. Its works If I want to access the first element:
var child = form.firstChild;
alert(child.nextSibling.nextSibling.nextSibling.innerHTML);
this returns the first radiobutton text.
But if I create a loop out of this
function getRadioBInfo() {
var form = document.getElementById("myform");
for (var i = 0; i < form.length; i++) {
var iForm = form[i];
var child = iForm.firstChild;
alert(child.nextSibling.nextSibling.nextSibling.innerHTML);
}
}
.. I get I TypeError: child is null
What is wrong with this code?
HTML
<form action="" name="deliver_form" id="myform" style="display: block;">
<input type="radio" name="delivering" id="radio1" value="deliver"> <label>label1</label><br>
<input type="radio" name="delivering" value="comeandtake"> <label>label2</label><br>
<input type="radio" name="delivering" value="express"> <label>label3</label>
</form>
I think you are looking for something like following.
var form = document.getElementById("myform");
for (var i = 0; i < form.length; i++) {
var child = form.getElementsByTagName('input')[i];
alert(child.nextSibling.nextSibling.innerHTML);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="deliver_form" id="myform" style="display: block;">
<input type="radio" name="delivering" id="radio1" value="deliver"> <label>label1</label><br>
<input type="radio" name="delivering" value="comeandtake"> <label>label2</label><br>
<input type="radio" name="delivering" value="express"> <label>label3</label>
</form>
Since you've tagged jquery, you could use:
$('[name=delivering']).each( function() {
alert( $(this).find('label').html() );
});
To get the label followed after the radio button you could try this:
function getRadioBInfo() {
var form = document.getElementById("myform");
var radios = form.querySelectorAll('input[type=radio]');
var i;
for (i = 0; i < radios.length; i++) {
var radio = radios[i];
console.log(radio.nextSibling.innerHTML);
}
}
getRadioBInfo();
pitfall: there shouldn't be whitespace between the radio or the button. Otherwise nextSibling returns text and not the label
demo
Why you are not getting by name
Try this
function getRadioBInfo() {
var arrRadioBtns = document.getElementsByName("delivering");
for (var i = 0; i < arrRadioBtns.length; i++) {
var btn = arrRadioBtns[i];
alert (btn.value);
}
}
Working Example
form[i] contains only radio buttons.If You want to take the labels Try using
var lbl = document.getElementsByTagName('label');
for (var i=0;i < lbl.length; i++){ lbl[i].innerHTML = 'radio' + i; }
and loop through the labels and change the text
Couple of observation
var form = document.getElementById("myform");
form will not be an array,Instead it will be a String,So you are iteration of the string.length;
You can use doucment.getElementsByName to get all radio buttons with common name
Hope this snippet will be useful
function getRadioBInfo() {
//Retun collection of radio button with same name
var _getRadio = document.getElementsByName("delivering");
// loop through the collection
for(var i = 0;i<_getRadio.length;i++){
//nextElementSibling will return label tag next to each radio input
console.log(_getRadio[i].nextElementSibling.innerHTML)
}
}
getRadioBInfo();
Jsfiddle

Get form values through JavaScript

This is my HJTML code. I don't know how to get values stored in filtertime[] using JavaScript and make them show on my screen.
<form action="index.php" method="post" >
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Morning"></div> <div class="f-txt-r">Morning</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Afternoon"></div> <div class="f-txt-r">Afternoon</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Evening"></div> <div class="f-txt-r">Evening</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Night"></div> <div class="f-txt-r">Night</div></div>
<div class="col-lg-12"><input type="submit" name="button" class="apply-filter" value="Apply Filter"></div>
</form>
<script>
var new = document.getElementsById("test").innerhtml
</script>
How can I get input values in JavaScript through value is stored in array as filtertime[]?
try
in your form
<form action="index.php" id="myform" method="post" >
in jQuery
var datastring = $("#myform").serialize();
By JS
var params = '';
for( var i=0; i<document.FormName.elements.length; i++ )
{
var fieldName = document.FormName.elements[i].name;
var fieldValue = document.FormName.elements[i].value;
// use the fields, put them in a array, etc.
// or, add them to a key-value pair strings,
// as in regular POST
params += fieldName + '=' + fieldValue + '&';
}
Add id in your form tag.
<form action="index.php" id="form_name" method="post" >
Use below code to get all form element by JS :-
document.forms["form_name"].getElementsByTagName("input");
Note:- Above Code will work only if you don't have selects or textareas in your form.
If you have assigned id in DOM element like below,
<input type="text" name="name" id="uniqueID" value="value" />
Then you can access it via below code:-
Javascript:-
var nameValue = document.getElementById("uniqueID").value;
If you have Radio button in your form, then use below code:-
<input type="radio" name="radio_name" value="1" > 1
<input type="radio" name="radio_name" value="0" > 0<br>
Javascript:-
var radios = document.getElementsByName('radio_name');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
Hope it will help you :)
this is the easiest way to get array of your form items
var arrValues = [];
for (var x =0; x < document.getElementsByClassName("morning").length ; x++)
{
arrValues.push(document.getElementsByClassName("morning")[x].checked);
}
To do that, the easiest way is to select all input with the "morning" class and after, foreach look if is checked :
var item = document.getElementsByClassName("morning"); // get all checkbox
var checkboxesChecked = []; // result array with ckecked ckeckbox
for (var i=0; i<item.length; i++) {
// if is checked add the value into the array
if (item[i].checked) {
checkboxesChecked.push(item[i].value);
}
}
console.log(checkboxesChecked);
In the "checkboxesChecked" array you have all the values of the checked box.

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/

document.activeElement doesn't work as expected on Chrome, what are the alternatives?

Hi,
I want to check/uncheck all the checkboxes with the same class as well as disable\enable the associated text fields when checking/unchecking a checkbox.
I managed to write a code using document.activeElement and document.getElementsByClassName that'll do exactly that, except that it doesn't work on Chrome. It's a reported bug in Chrome that it returns body instead of the actual activeElement unless the activeElement is a text field.
Is there a workaround that I can use until the bug is fixed?
My code:
JS:
function changeAll(variable) {
var current = document.activeElement;
var checkboxes = variable + "_g";
var text = variable + "_v";
var i;
if (current.checked === true) {
for (i = 0; i < document.getElementsByClassName(checkboxes).length; i++) {
document.getElementsByClassName(checkboxes)[i].checked = true;
}
for (i = 0; i < document.getElementsByClassName(text).length; i++) {
document.getElementsByClassName(text)[i].disabled = false;
}
} else {
for (i = 0; i < document.getElementsByClassName(checkboxes).length; i++) {
document.getElementsByClassName(checkboxes)[i].checked = false;
}
for (i = 0; i < document.getElementsByClassName(text).length; i++) {
document.getElementsByClassName(text)[i].disabled = true;
}
}
}
HTML:
<input type="checkbox" class="y_g" onClick="changeAll('y')">
<input type="text" class="y_v" disabled>
<input type="checkbox" class="y_g" onClick="changeAll('y')">
<input type="text" class="y_v" disabled>
<br>
<input type="checkbox" class="x_g" onClick="changeAll('x')">
<input type="text" class="x_v" disabled>
<input type="checkbox" class="x_g" onClick="changeAll('x')">
<input type="text" class="x_v" disabled>
Pass in the reference
HTML:
<input type="checkbox" class="y_g" onClick="changeAll(this,'y')">
JavaScript:
function changeAll(current, variable) {
//var current = document.activeElement;
ideally you would not be using inline events.

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