Take input value from form with loop and create array - javascript

I have problem with JavaScript function. How can I take the value from the form inputs with loop ?
I try something like
var values =[];
for (var h=1; h<=arrange;++h){
values[h]=parseFloat($('#inputr2"+h+"').val());
}
How can I add h in the id , as inputr20 (if h=0) ,inputr21 (h=1) ,anyone can help ?

try
var values =[];
for (var h=1; h<=arrange;++h){
values[h]=parseFloat($(String("#inputr2"+h)).val());
}

Array's index are 0 based. You have to assign the value to the index h-1. You do not need to decrease that, if you start the loop from 0. Also the string id you are generating is not properly formatted. You can try the following way:
var values =[];
var arrange = 2
for (var h=0; h<arrange;h++){
values[h]=parseFloat($("#inputr2"+h).val());
//Or you can simply use push() which does not require index.
//values.push(parseFloat($("#inputr2"+h).val()));
}
console.log(values)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputr20" value="11.11"/>
<input id="inputr21" value="22.22"/>
If you want get all the input values having id Starts With, you can use map() and get() like the following way:
var values = $('[id^=inputr2]').map((i, el) => parseFloat($(el).val())).get();
console.log(values)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputr21" value="11.11"/>
<input id="inputr22" value="22.22"/>

Related

Split jQuery collection into an array of individual jQuery objects

I am wondering if there is a way to split a jQuery selector which contains a collection of elements into an array of selectors, one for each element. For example, I have:
fields = row.find('input');
which returns a selector containing multiple input elements. I know I can use
fields.eq(index).val()
to access individual values, but is there an easy way to construct or convert fields to an array of selectors so I can just use
fields[index].val()
Edit:
Yes I realize you can use .toArray(), but as has been pointed out below, that returns an array of DOM elements. Then you'd have to loop through to convert these to selectors - too much extra work.
How about a small plugin to do this for you?
$.fn.toJqArray = function(){
var arr = [];
$(this).each(function(){
arr.push($(this));
});
return arr;
};
var inputs = $('input').toJqArray();
var value = inputs[0].val();
Here's a fiddle with usage.
You can use both jQuery toArray() function or jQuery.makeArray() function.
Both of them will return an array of DOM elements.
The difference is that toArray function converts only jQuery result object to an array:
$("p").toArray(); // correct
$.makeArray is more multipurpose and complicated. It converts any array-like objects to a proper JS array.
For example,
var elems = document.getElementsByTagName("p");
actually returns array-like nodeList, but not an array.
You cannot do:
var elems = document.getElementsByTagName("div");
elems.reverse(); // error. reverse() is not part of nodeList
However, you can do
var elems = document.getElementsByTagName("div");
var arr = $.makeArray(elems);
arr.reverse(); // ok. arr is a JS array which has reverse() function
However, in case of converting jQuery selection result - there is no difference between them.
Take a look at the following code snippet which makes a jQuery selection, converts this jQuery object to two JS arrays in two different ways and works with non-jQuery DOM innerHTML property.
var pJquery = $("p");
var pArray1 = pJquery.toArray();
var pArray2 = $.makeArray(pJquery);
document.getElementById('output').innerHTML = pArray1[1].innerHTML;
document.getElementById('output').innerHTML += pArray2[2].innerHTML;
p
{
color: #FF0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>1</p>
<p>2</p>
<p>3</p>
<div id="output"></div>
IF you use pure javascript, you access to inputs by an array, but if you need with jQuery you can make a loop:
var arrFields = [];
fields.each(function() {
arrFields.push($(this).val());
});
console.log(arrFields);
good luck!
You can do this:
var $input = $("input");
var $$input = $input.map(function() {
return $(this);
}).get();
console.log($input instanceof Object); // true
console.log($input instanceof jQuery); // true
console.log($$input instanceof Array); // true
$input.eq(3).val("test");
$$input[3].val("test");
But this is absurd.
You could use jQuery .toArray():
var arr = fields.toArray();
console.log(arr[0].value)
You can't use .val() here, but .value will work fine.
A small example/proof of concept:
var fields = $('input').toArray();
$.each(fields, function(i, o) {
console.log(o.value + ' == ' + fields[i].value)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="a" value="a" />
<input name="b" value="b" />
<input name="c" value="c" />
<input name="d" value="d" />
Yes you could use .toArray()
var fieldsArray = [];
fieldsArray = fields.toArray();
Each html element, if it don't posess an id, isn't guarentee to have a unique selector.

Passing array of array elements to a function

I've been searching for an answer of this concept for a whole day and finally gave up and decided to ask it here.
Here's the concept:
I have a set of fields which are arrayed, I want that set of fields to be inside of array so that I can use a standard function for saving a module based on the fields involved and another param to check which to save.
Sample code:
module1.php
<?php
$i=0;
while($i<5){
?>
<input type="text" name="field1[$i]" />
<input type="text" name="field2[$i]" />
<input type="text" name="field3[$i]" />
<?php
$i++;
}
?>
<input type="button" name="process"
onclick="checkFields(['field1', 'field2', 'field3'], 'module1');" />
<script>
function checkFields(f, m){
var fn = f.length;
alert(fn); //Output is 3
for(i=0; i<fn; i++){
var nfn = f[i].length; //Here's where it's not working
alert(nfn); //Output should be 5
}
}
</script>
So, that part with comment is the thing I can't figure how to do, I tried using getElementById, getElementsByName but it's not working.
Or is there any possibility that I can pass an array of elements like this: array(field1, field2, field3) to a function?
Edit: I added a while loop statement to make the concept more comprehensive.
<script>
function checkFields(f, m){
var fn = f.length;
alert(fn);
for(i=0; i<=fn; i++){
var nfn = f[i].length; //Here's where it's not working
alert(nfn);
}
}
</script>
You should be applying the indexer on the f parameter, instead of the fn variable which is an integer.
fn is the length of your array, not your array. You should be using f
Change...
var nfn = fn[i].length; //Here's where it's not working
To...
var nfn = f[i];
Also, you will find that the for loop will fail, as i will reach fn but the array stops at fn-1
So change...
for(i=0; i<=fn; i++){
To...
for(i=0; i<fn; i++){
f[i] still points to just the incorrect input names. You don't really get access to the input field.
Do this:
var inputName = f[i] + "[]";//remember the input name is field1[] and not field1.
var value = document.querySelector( "input[name='"+inputName+"']" ).value;
the value here is just the input text of the input field and not really an array. If you have multiple fields with the same name, then use document.querySelectorAll method to get all the input fields and then iterate to get the values one by one.
To help you understand better, consider these 2 options:
Option 1:
html:
<input name="field1[]" />
<input name="field1[]" />
access the value:
var inputFields = document.querySelectorAll("input[name='field1[]']");
var values = [];
for (var j = 0; j < inputFields.length; j++) {
var val = inputFields[i].value;
values.push(val);
}
Option 2:
html:
<input name="field1[0]" />
<input name="field1[1]" />
access the value:
var values = [];
var j = 0;
var inputField;
while (true) {
var inputField = document.querySelector("input[name='field1[" + j + "]']");
if (!inputField) break;
values.push(inputField.value);
j++;
}
Note that, in option 1, there are multiple fields with the same "name" and in option 2, there are multiple fields with unique names.

jquery - add to array

Why this not working?
var inputs = new Array();
$("input").each(function(){
input = $(this).val();
})
console.log(input);
how to correctly use arrays in jQuery? Like as PHP?
I assume what you are trying to do is get an array of the values of all the <input> elements on your page. What you'll need to do is iterate over all the elements using the .each() function and append each value to your inputs array.
Try this -
var inputs = new Array();
$("input").each(function(){
inputs.push($(this).val());
})
console.log(inputs);
You need to use the push() function to add an element to an array.
fiddle demo
References -
Array push method on MDN
As a final note, here is a shorthand way to define a new array -
var inputs = [];
That line is functionally identical to -
var inputs = new Array();
Use Array.push
var inputs = new Array();
$("input").each(function(){
inputs.push($(this).val());
})
Also note the variable differences .. input != inputs

Dynamically create a two dimensional Javascript Array

Can someone show me the javascript I need to use to dynamically create a two dimensional Javascript Array like below?
desired array contents:
[["test1","test2","test3","test4","test5"],["test6","test7","test8","test9","test10"]]
current invalid output from alert(outterArray):
"test6","test7","test8","test9","test10","test6","test7","test8","test9","test10"
JavaScript code:
var outterArray = new Array();
var innerArray = new Array();
var outterCount=0;
$something.each(function () {
var innerCount = 0;//should reset the inner array and overwrite previous values?
$something.somethingElse.each(function () {
innerArray[innerCount] = $(this).text();
innerCount++;
}
outterArray[outterCount] = innerArray;
outterCount++;
}
alert(outterArray);
This is pretty cut and dry, just set up a nested loop:
var count = 1;
var twoDimensionalArray =[];
for (var i=0;i<2;i++)
{
var data = [];
for (var j=0;j<5;j++)
{
data.push("Test" + count);
count++;
}
twoDimensionalArray.push(data);
}
It sounds like you want to map the array of text for each $something element into an outer jagged array. If so then try the following
var outterArray = [];
$something.each(function () {
var innerArray = [];
$(this).somethingElse.each(function () {
innerArray.push($(this).text());
});
outterArray.push(innerArray);
});
alert(outterArray);
A more flexible approach is to use raw objects, they are used in a similar way than dictionaries. Dynamically expendables and with more options to define the index (as string).
Here you have an example:
var myArray = {};
myArray[12]="banana";
myArray["superman"]=123;
myArray[13]={}; //here another dimension is created
myArray[13][55]="This is the second dimension";
You don't need to keep track of array lengths yourself; the runtime maintains the ".length" property for you. On top of that, there's the .push() method to add an element to the end of an array.
// ...
innerArray.push($(this).text());
// ...
outerArray.push(innerArray);
To make a new array, just use []:
innerArray = []; // new array for this row
Also "outer" has only one "t" :-)
[SEE IT IN ACTION ON JSFIDDLE] If that $something variable is a jQuery search, you can use .map() function like this:
var outterArray = [];
var outterArray = $('.something').map(function() {
// find .somethingElse inside current element
return [$(this).find('.somethingElse').map(function() {
return $(this).text();
}).get()]; // return an array of texts ['text1', 'text2','text3']
}).get(); // use .get() to get values only, as .map() normally returns jQuery wrapped array
// notice that this alert text1,text2,text3,text4,text5,text6
alert(outterArray);​
// even when the array is two dimensional as you can do this:
alert(outterArray[0]);
alert(outterArray[1]);
HTML:
<div class="something">
<span class="somethingElse">test1</span>
<span class="somethingElse">test2</span>
<span class="somethingElse">test3</span>
</div>
<div class="something">
<span class="somethingElse">test4</span>
<span class="somethingElse">test5</span>
<span class="somethingElse">test6</span>
</div>
Here you can see it working in a jsFiddle with your expected result: http://jsfiddle.net/gPKKG/2/
I had a similar issue recently while working on a Google Spreadsheet and came up with an answer similar to BrianV's:
// 1st nest to handle number of columns I'm formatting, 2nd nest to build 2d array
for (var i = 1; i <= 2; i++) {
tmpRange = sheet.getRange(Row + 1, Col + i, numCells2Format); // pass/fail cells
var d2Arr = [];
for (var j = 0; j < numCells2Format; j++) {
// 1st column of cells I'm formatting
if ( 1 == i) {
d2Arr[j] = ["center"];
// 2nd column of cells I'm formatting
} else if ( 2 == i ) {
d2Arr[j] = ["left"];
}
}
tmpRange.setHorizontalAlignments( d2Arr );
}
So, basically, I had to make the assignment d2Arr[index]=["some string"] in order to build the multidimensional array I was looking for. Since the number of cells I wanted to format can change from sheet to sheet, I wanted it generalized. The case I was working out required a 15-dimension array. Assigning a 1-D array to elements in a 1-D array ended up making the 15-D array I needed.
you can use Array.apply
Array.apply(0, Array(ARRAY_SIZE)).map((row, rowIndex) => {
return Array.apply(0, Array(ARRAY_SIZE)).map((column, columnIndex) => {
return null;
});
});`

Populate dropdown select with array-with multiple options

So I'm trying to populate a dropdown with the states, the value for the option should be the two characters value, and the text for the option should be the full state's name, using the code below is returning a value of 0,1,2,3... and returning all the options in the var as the text.
var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR",...];
$.each(states, function(val, text) {
$('#selector').append( $('<option> </option>').val(val).html(text) )
});
Try this, using an object for states instead of an array. Same results, but it's more clear what's what and you're less likely to have problems if you accidentally skip a name or abbreviation:
var states = {
"Select State":"",
"Alabama":"AL",
"Alaska":"AK",
"Arizona":"AZ",
"Arkansas":"AR"
};
var val, text;
for (text in states) {
val = states[text];
$('<option/>').val(val).text(text).appendTo($('#selector'));
};
http://jsfiddle.net/g59U4/
The problem is that the callback function provided to .each results in val containing the index of the current iteration (e.g. 0, 1, 2 etc.) and text containing the value of that index of the array.
To achieve what you are trying to, you would probably be better off with a normal for loop:
for(var i = 0; i < states.length; i+=2) {
$("#selector").append($('<option> </option>').val(states[i+1]).html(states[i]));
}
You would be even better off caching the jQuery object containing #selector outside of your loop, so it doesn't have to look it up every iteration.
Here's a working example of the above.
Another option would be to use an object instead of an array, using the state name or abbreviation as the keys, and the other as the values. Edit: just like #mblase75 has done
Well you have the jQuery.each function arguments confused. The first is the index of the value in the array, and the second in the value itself. What you need to do is something like:
$.each(states, function(index) {
if(index%2 > 0) {
//continue, basically skip every other one. Although there is probably a better way to do this
return true;
}
$('#selector').append( $('<option> </option>').val(states[index+1]).html(states[index]) )
});
That would be really straightforward if your array had two dimensions. Considering you really need to use the one-dimensional array you presented, you could do this:
var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR"];
for(var i=1; i<states.length; i+=2) {
$('#selector').append( $('<option value="' + states[i] + '">' + states[i-1] + '</option>').val(val).html(text) )
}
If you changed your array to be an array of objects, you could do something like this -
var states = [{"text":"Select State","val":""},{"text":"Alabama","val":"AL"}]; //etc
$.each(states, function(val, statedata) {
$('#selector').append( $('<option> </option>').val(statedata.val).html(statedata.text) )
});
This change passes a JavaScript object in to the callback each time. The object has text and val properties and is passed in to the callback as the statedata parameter. The val parameter holds the current index position of the array so it is not required to populate the select box.
Demo - http://jsfiddle.net/sR35r/
I have a similar situation populating a select list with a two-dimensional array as the result of an $.ajax callback ....
JSON ...
[["AL","Alabama"],["AK","Alaska"],["AS","American Samoa"],["AZ","Arizona"] ...
var stateOptions = $('#state');
var html ='';
for (var i =1; i<data.length; i++){
html+= '<option value="' +data[i][0]+ '">' +data[i][1]+ '</option>';
}
stateOptions.append(html);
<form name="form" id="form">
<select name="state" id="state">
<option value=''>State</option>
</select>
</form>

Categories

Resources