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

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.

Related

Javascript using For loop for false

I'm learning now for loops, and as an example I was given in a game this (with '.result-paras' being p classes):
<div class="form">
<label for="guess-field">Enter a guess: </label>
<input type="text" id="guess-field" class="guess-field">
<input type="submit" value="Submit guess" class="guess-submit">
</div>
<div class="result-paras">
<p class="guesses"></p>
<p class="last-result"></p>
<p class="low-or-high"></p>
</div>
const resetParas = document.querySelectorAll('.result-paras');
for (let i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
I want to try to copy it on an input type which I want to disable, meaning I want 2 input fields to be disabled using a loop and I'm having trouble getting it to work, would really appreciate your help:
const disableParas = document.querySelectorAll('.form');
for (let i = 0; i < disableParas ; i++ ) {
disableParas[i].disabled = false;
}
When using a for loop to iterate over a list like that, you often use it like this, counting up a variable up to the length of the list:
const disableParas = document.querySelectorAll('.form');
for (let i = 0 ; i < disableParas.length; i++ ) {
disableParas[i].disabled = false;
}
The first part of the for loop is what you do initially, the second part is the condition to stop the loop and the last part is executed each iteration of the loop.

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

Making checkboxes checked using same id using Javascript

This is my code to make check boxes checked with same id
<input type="checkbox" name="MassApprove" value="setuju2" />
<input type="checkbox" name="MassApprove" value="setuju3" />
<input type="checkbox" name="MassApprove" value="setuju4" />
<input type="checkbox" name="MassApprove" value="setuju5" />
<input type="submit" value="Next Step" name="next" />
And This is my javascript code. I need to make this checkboxes as checked when am trigger this function. Help me!..
function doMassApprove(massApproveFlag) {
var confirmAlert = confirm("Do You Need Mass Approve !..");
var massApprove = document.getElementById("MassApprove").length();
if (confirmAlert == true) {
//alert(massApproveFlag);
for (var i = 0; i < massApprove; i++) {
document.getElementById("MassApprove").checked = true;
}
} else {
document.getElementById("headerMassApprove").checked = false;
}
}
IDs in HTML must be unique.
As you have already specified the name MassApprove, use Document.getElementsByName(),
Returns a nodelist collection with a given name in the (X)HTML document.
Which you can iterate using simple for loop
function doMassApprove(massApproveFlag) {
var confirmAlert = confirm("Do You Need Mass Approve !..");
if (confirmAlert) {
//Get elements with Name
var massApproves = document.getElementsByName("MassApprove");
//Iterate and set checked property
for (var i = 0; i < massApprove.length; i++) {
massApproves[i].checked = true;
}
} else {
document.getElementById("headerMassApprove").checked = false;
}
}
you do not have the same ID and should not since ID must be unique. You have the same NAME and that is fine. -
Do not user getElementById for names, instead use document.getElementsByName which will return a collection you can loop over
Like this
function doMassApprove(massApproveFlag) {
var massApprove = confirm("Do You Need Mass Approve !..");
if (massApprove) {
var checks = document.getElementsByName("MassApprove");
for (var i=0; i < checks.length; i++) {
checks[i].checked = massApprove; // or perhaps massApproveFlag?
}
}
else {
document.getElementById("headerMassApprove").checked = false;
}
}
Just for the heck of it, you can use some modern browser goodness:
Array.prototype.forEach.call(document.querySelectorAll('[name=MassApprove]'), function(cb){cb.checked = true});
and with arrow functions:
Array.prototype.forEach.call(document.querySelectorAll('[name=MassApprove]'), cb => cb.checked=true);

JavaScript - get value from multiple inputs in an array

I am trying to get the value from muliple inputs with the same id in an array.
I already used the forum, but haven't find a solution for me.
Exmaple
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
var elem = document.getElementById("webcampics");
var names = [];
for (var i = 0; i < elem.length; ++ i) {
names += elem[i]+'|';
}
var webcamval = names;
You shouldn't have elements with identical id's within the document. ID's have to be unique throughout your entire markup, by specification. If you do it anyways, methods like document.getElementById will only match the very first occurence for instance.
Use a class instead of ids.
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
var inputs = document.getElementsByClassName( 'webcampics' ),
names = [].map.call(inputs, function( input ) {
return input.value;
}).join( '|' );
Demo: http://jsfiddle.net/QgJrq/
What you are asking for is wrong very wrong, it is recommended IDs should be unqiue, but for learners sake here's what you would do
var elem = document.getElementsByTagName("input");
var names = [];
for (var i = 0; i < elem.length; ++i) {
if (typeof elem[i].attributes.id !== "undefined") {
if (elem[i].attributes.id.value == "webcampics") {
names.push(elem[i].value);
}
}
}
var webcamval = names;
http://jsfiddle.net/5vamG/
Due to someone down voting after giving a full explanation why the above mentioned method is wrong, however does exactly what youve asked for, here's the correct method.
change all the inputs id to class
var elem = document.getElementsByClassName("webcampics");
var names = [];
for (var i = 0; i < elem.length; ++i) {
if (typeof elem[i].value !== "undefined") {
names.push(elem[i].value);
}
}
}
var webcamval = names;
http://jsfiddle.net/5vamG/1/
You shouldn't have more than one element with the same id.
getElementById returns exactly one element; use getElementsByName which will return the list you seek.

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