Loop radio-button form javascript - 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

Related

Is it possible to use multiple for loop at same time?

I want to create a html form, it have 2 group(Name and fruit), each group have two check boxes, When user clicks the checkbox that input name are user_checkbox[] and fruit_checkbox[] , its will do something,i need to use array and for loop to get the user which group of checkboxes was checked , but it seems not to allow me use multiple for loop.
My Html File
//group1
<input name="user_checkbox[]" type="checkbox" value="Peter" onclick="showinputtext();" >Peter
<input name="user_checkbox[]" type="checkbox" value="Billy" onclick="showinputtext();" >Billy
//group2
<input name="fruit_checkbox[]" type="checkbox" value="Apple" onclick="showinputtext();" >Apple
<input name="fruit_checkbox[]" type="checkbox" value="Banner" onclick="showinputtext();" >Banana
My Javascript file
function showinputtext() {
var name = document.getElementsByName("user_checkbox[]");
var fruit = document.getElementsByName("fruit_checkbox[]");
for (var n = 0; n < name.length; n++) && for (var f = 0; f < fruit.length; f++) {
if(name[n].checked && fruit[f].checked){
dosomething..................
}
}
but it is not work for me, any idea?? thx
Try nested for loops.
function showinputtext(){
var name = document.getElementsByName("user_checkbox[]");
var fruit = document.getElementsByName("fruit_checkbox[]");
for (var i = 0; i < name.length; i++) {
for (var j = 0; j < fruit.length; j++) {
if(name[i].checked && fruit[j].checked){
alert("ok");
}
}
}
};
if you use jquery
try it :
Example
$("[type='checkbox']").on("click",function(){
var name = document.getElementsByName("user_checkbox[]");
var fruit = document.getElementsByName("fruit_checkbox[]");
for (var i = 0; i < name.length; i++) {
for (var j = 0; j < fruit.length; j++) {
if(name[i].checked && fruit[j].checked){
alert("ok");
}
}
}
});
Why not use forEach? Looks a bit nicer and does the same job in this instance:
function showInputText() {
var nameCheckboxes = document.getElementsByName("user_checkbox[]");
var fruitCheckboxes = document.getElementsByName("fruit_checkbox[]");
nameCheckboxes.forEach(function(nameCheckbox) {
fruitCheckboxes.forEach(function(fruitCheckbox) {
if (nameCheckbox.checked && fruitCheckbox.checked) {
alert ("ok");
};
});
});
I renamed the variables and the function to make this a bit more readable!
Just remember to change the function calls in the onclick attributes if you go for this approach:
// Group 1
<input name="user_checkbox[]" type="checkbox" value="Peter" onclick="showInputText();" >Peter
<input name="user_checkbox[]" type="checkbox" value="Billy" onclick="showInputText();" >Billy
// Group 2
<input name="fruit_checkbox[]" type="checkbox" value="Apple" onclick="showInputText();" >Apple
<input name="fruit_checkbox[]" type="checkbox" value="Banner" onclick="showInputText();" >Banana
However, reading your post, you might not need to do this at all. It seems unnecessary to iterate through both groups in a nested loop. Why not instead add each item to an array and "Do stuff" with both when the form is submitted?
I would change your checkboxes to have a fruit-input and user-input class:
<input type="checkbox" name="peter" class="user-input">
<input type="checkbox" name="banana" class="fruit-input">
Then I would add an event listener to the fruit-input and user-input elements which listen for changes to the checkboxes. When a change event occurs it then checks if the input has been checked or not, and it will then add or remove from either the selectedFruits or selectedUsers arrays:
document.getElementsByClassName("fruit-input")
.forEach(function(input){
input.addEventListener("change", selectFruit);
});
document.getElementsByClassName("user-input")
.forEach(function(input){
input.addEventListener("change", selectUser);
});
var selectedFruits = [];
var selectedUsers = [];
function selectFruit() {
var fruit = this.getAttribute("name");
if (this.checked) {
selectedFuits.push(fruit);
} else {
selectedFruits.remove(fruit);
}
}
function selectUser() {
var user = this.getAttribute("name");
if (this.checked) {
selectedUsers.push(user);
} else {
selectedUsers.remove(user);
}
}
Notice how the functions grab the value to add to the arrays from the input element's name attribute. Your current name attributes are invalid as they should really be unique.
It is even possible to refactor my suggestion above to have one generic input field listener and determine the array to add to based on a data attribute or something. But this is a good starting point.
After all this you can do whatever you need with the selectedFruits or selectedUsers arrays.
Try placing the second for loop inside the first one, like so
for (var n = 0; n < name.length; n++) {
for (var f = 0; f < fruit.length; f++) {
if(chboxsEng_single[n].checked && chboxsEng_fruit[f].checked){
dosomething..................
}
}
}
Be aware that this will go through every single value of f a total of n times, which may or may not be behaviour that you desire, it's not clear in the question.

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/

Display value of checked check boxes 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

Accessing radio elements in forms in javascript

I have a use case where the the number of radio buttons can be 1 or more, what is the best practice to check
i.e
var radioElements = document.forms["formname"].elements["abc"];
for(var i=0; i < radioElements.length; i++) {
if(radioElements[i].checked) {
alert("blah..");
break;
}
}
This works when the DOM has
<form name="formname">
<input type=radio name=abc id=abc value=aaa/>
<input type=radio name=abc id=abc value=bbb/>
</form>
But fails to work when it has only one radio element
<form name="formname">
<input type=radio name=abc id=abc value=aaa/>
</form>
How can I make the above javascript work in both these cases.
You could use getElementsByName. This method always returns a collection which you can iterate over:
var radioElements = document.getElementsByName("abc");
for(var i=0; i < radioElements.length; i++)
{
if(radioElements[i].checked)
{
alert("blah..");
break;
}
}
See an example of this in action at jsfiddle.net/L6SKx/.
You're accessing the radio buttons wrong:
var radios = document.forms['formname'].abc;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert('#' + i + ' is checked, with value ' + radios[i].value);
}
}
As well, with your multiple radio button example, it's invalid to have the same ID on two or more separate DOM elements. An ID has to be unique on the page.

Categories

Resources