JavaScript - get value from multiple inputs in an array - javascript

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.

Related

getElementByID.readOnly in array

Im trying to create a list of input ID's and use it in array, to make them readOnly - but the result is error -> "cannot read property 'readOnly' of null".
Can you give me a hint what I should change?
script language="javascript" type="text/javascript">
$(document).ready(function () {
$(function(){
var index, len;
$.get('/SomeList.txt', function(data){
var SomeList = data.split('\n');
for (index = 0, len = SomeList.length; index < len; index++) {
document.getElementById(SomeList[index]).readOnly = true;
}
});
});
});
</script>
and txt file contains name of input ID:
TextFieldName
TextFieldEmail
TextFieldDepartment
TextFieldOffice
Assuming you have some elements with the given IDs you must check if the element exists first before doing
document.getElementById(SomeList[index]).readOnly = true;
so replace that line with
var myElement = document.getElementById(SomeList[index]);
if(myElement == null) {
return;
}
myElement.readOnly = true;
That should work like following example where the IDs come from an array and the second one will not mach because of xxxxx so it's not readonly. But all the others are.
var dataArray = [
'TextFieldName',
'TextFieldEmailxxxxx',
'TextFieldDepartment',
'TextFieldOffice'
];
dataArray.forEach(function(id){
var myElement = document.getElementById(id);
if(myElement == null) {
return;
}
myElement.readOnly = true;
});
<input id="TextFieldName" type="text">
<input id="TextFieldEmail" type="text">
<input id="TextFieldDepartment" type="text">
<input id="TextFieldOffice" type="text">
var id_array=["email","country"];
for (i = 0; i <id_array.length; i++) {
document.getElementById(id_array[i]).readOnly = true;
}
Email: <input type="text" id="email" value="test#mail.com"><br>
Country: <input type="text" id="country" value="Norway" >
it is working fine in my case.
i think there may be whitespace in your array items because your are reading them from file.so try to trim array items.
and make sure you assign id's to input elements

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.

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

JavaScript form same values

How can I make a form so they cannot repeat the same values in the Input?
I tried a way like:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num1').value;
var textform = [text1,text2];
if (
text1 == text2 ||
text2 == text1
) {
alert("repeated numbers");
return false;
}
But this is gets me into two troubles:
- If I put no value, it will say: Repated Numbers
- If I want to make this for 100 form values, it takes a lot of code
You could give all of your text elements the same class, and grab their values by class name to simplify building the array of text values.
<input type="text" class="checkDupe" id="input1" />
<input type="text" class="checkDupe" id="input2" />
Then grab their values in javascript
var checkDupes = document.getElementsByClassName('checkDupe');
var textArray = [];
for(var i = 0; i < checkDupes.length; i++){
textArray.push(checkDupes[i].value);
}
Now that we have an array of values that they entered, check to see if any of them repeat by sorting the array, and seeing if any two elements side-by-side are the same.
textArray.sort();
var dupes = false;
for(var i = 0; i < textArray.length; i++){
if(textArray[i] === textArray[i + 1]) dupes = true;
}
If we find any duplicates, let the user know.
if(dupes) alert('Repeated numbers!');
You could do something like this:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num2').value;
var textform = [text1, text2];
var seen = {};
textform.forEach(function(value) {
if (seen[value]) {
alert('Bad!');
}
seen[value] = true;
});
In the code above, we loop over each value in the array. The first time we encounter it, we push it into a map. Next time (if) we hit that value, it will exist in the map and it will tell us we've seen it before.
If you give all the input's a common class then you quickly loop through them.
The HTML:
<input type="text" name="num1" class="this that number"></input>
<input type="text" name="num2" class="this number"></input>
<input type="text" name="num3" class="that number"></input>
<input type="text" name="num4" class="number"></input>
<input type="text" name="num5" class=""></input> <!-- we don't want to check this one -->
<input type="text" name="num6" class="number that this"></input>
<input type="text" name="num7" class="this that number"></input>
The JavaScript:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then let the user know they are a bad person
// and stop
if(tracker[inValue])
{
alert("You are a bad person!");
return;
}
// track the value
tracker[inValue] = true;
}
You could also enhance this to let the user know which inputs have duplicate values:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then error them
if(tracker[inValue])
{
// mark the current input as error
ins[i].className += " error";
// mark the first found instance as an error
ins[tracker[inValue]].className += " error";
}
// save the index so we can get to it later if a duplicate is found
tracker[inValue] = i;
}
Here's a way of doing it that automatically picks up all the text inputs in your document and validates based on what you're looking for. Would be simple enough to expose the valid value and make this the validation handler (or part of one) that handles a form submission.
<meta charset="UTF-8">
<input id="num1" type="text" value="foobar1">
<input id="num2" type="text" value="foobar2">
<input id="num3" type="text" value="foobar3">
<input id="num4" type="text" value="foobar4">
<input id="num5" type="text" value="foobar5">
<button onClick="checkValues();">Validate</button>
<script>
function checkValues() {
var inputs = document.getElementsByTagName('input');
arrInputs = Array.prototype.slice.call(inputs);
var valid = true;
var valueStore = {};
arrInputs.forEach(function(input) {
if (input.type == 'text') {
var value = input.value.toUpperCase();
if (valueStore[value]) {
valid = false;
} else {
valueStore[value] = true;
}
}
});
if (valid) {
alert('Valid: No matching values');
} else {
alert('Invalid: Matching values found!');
}
}
</script>
With jquery you can iterate directly over the inputs.
<form>
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<button>
TEST
</button>
</form>
function checkValues(){
var used = {};
var ok = true;
$('form input[type="text"]').each(function(){
var value = $(this).val();
if(value !== ""){
if(used[value] === true){
ok = false;
return false;
}
used[value] = true;
}
});
return ok;
}
$('button').click(function(event){
event.preventDefault();
if(!checkValues()){
alert("repeated numbers");
};
});
https://jsfiddle.net/8mafLu1c/1/
Presumably the inputs are in a form. You can access all form controls via the form's elements collection. The following will check the value of all controls, not just inputs, but can easily be restricted to certain types.
If you want to include radio buttons and checkboxes, check that they're checked before testing their value.
function noDupeValues(form) {
var values = Object.create(null);
return [].every.call(form.elements, function(control){
if (control.value in values && control.value != '') return false;
else return values[control.value] = true;
});
}
<form id="f0" onsubmit="return noDupeValues(this);">
<input name="inp0">
<input name="inp0">
<input name="inp0">
<button>Submit</button>
</form>
For old browsers like IE 8 you'll need a polyfill for every.
You can simply get all inputs iterate them twice to check if they are equals
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
for (j = i + 1; j < inputs.length; j++) {
if (inputs[i].value === inputs[j].value) {
console.log('value of input: ' + i + ' equals input: ' + j);
}
}
}
<input value="56" />
<input value="12" />
<input value="54" />
<input value="55" />
<input value="12" />

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);

Categories

Resources