How can I store multiple sets of input values in JS? - javascript

Consider the following pairs of inputs
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
The number of pairs of inputs on a page is dynamic, not fixed.
I wish to loop through all pairs and store values as pairs to be output later into a table for example.
I've been trying to do it with jQuery's each() but I can't figure it out fully.
var detail = [];
//var detail = {};
$('input').each(function(index) {
detail[index] = $(this).val();
//detail.index = $(this).val();
});
console.log(detail);
This outputs
["iphone", "10", "macbook", "5"]
And it's not what I need.
I'm used to PHP, so what is the correct approach in JS/jQuery to store the pairs of inputs as a multidimensional associative array/object?

You can iterate over the elements with class item_name and create an array of objects that each have a name and qty property.
You can create this array more easily using jQuery's .map():
var details = $('.item_name').map(function() {
return {
name: $(this).val(),
qty: $(this).next('.item_qty').val()
};
}).get();
console.log(details);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">

The equivalent of an associative array in javascript is an object (both act as a dictionary)
The problem you have is that your html describes a key and a value as inputs in a flat list, so when you enumerate them with your JQuery .each() you get them back all in one list.
[key, value, key, value]
what you most likely want is an object like:
var obj = {
key: value,
key: value
}
Then you can get at say the 'macbook' property like so
obj.macbook or obj['macbook']
You can achieve this by either looping through the list two at a time and adding them to the object, or by restructing your html to have both the key and value inputs inside another element e.g.
<div class="item">
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
</div>
<div class="item">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
</div>
Then you can do something like this:
var items = {}
$('.item').each(function(){
var key = $(this).find('.item_name').val()
var value = $(this).find('.item_qty').val()
items[key] = value;
})

var val = $("input.item_name").map(function(){
obj = {}
obj[$(this).val()] = $(this).next("input.item_qty").val();
return obj;
}).get()
console.log(val)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
Use .map()

You can use recursion, Array.prototype.slice() to slice two <input> elements at each function call, populate an object with key, value pairs until <input> elemnents .length is reached
var [obj, n] = [{}, 2];
var inputs = $("input[type=text]");
var res = (function re(i) {
if (i + n <= inputs.length) {
var [key, prop] = Array.from(inputs).slice(i, i + n).map(({value}) => value)
obj[key] = prop;
i += n;
return re(i)
} else {
return obj
}
})(0);
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">

You can try a quick and "dirty" solution:
Ref: for each input type get value with javascript
You were on the right track with .getElementById, but you want instead, .getElementsByName.
var els = document.getElementsByName("filter[]");
for (var i = 0; i < els.length; i++)
alert(els[i].value);
<input id="filter_15" type="checkbox" name="filter[]" value="15">
<input id="filter_16" type="checkbox" name="filter[]" value="16">
<input id="filter_17" type="checkbox" name="filter[]" value="17">
Or, follow this: jQuery .each() with input elements
To extract number :
var arrNumber = new Array();
$('input[type=number]').each(function(){
arrNumber.push($(this).val());
})
To extract text:
var arrText= new Array();
$('input[type=text]').each(function(){
arrText.push($(this).val());
})
Edit : .map implementation
var arrText= $('input[type=text]').map(function(){
return this.value;
}).get();

Related

Get an object from a DomElement Node without frameworks

I have an element in my page:
<form>
<div data-id="x">
<label>field 1</label>
<input name="field1" type="text" value="Foo" />
<label>field 2</label>
<input name="field2" type="number" value="5" />
</div>
<div data-id="y">
<label>field 1</label>
<input name="field1" type="text" value="Foo" />
<label>field 2</label>
<input name="field2" type="number" value="5" />
</div>
...other 100 inputs...
</form>
I'm looking for a javascript script like that:
var theElement = document.querySelector('[data-id="x"]');
var myObject = theElement.toObject();
And the object must looks like
{"field1":"Foo","field2":5}
I can't use the FormData strategy because I need a very small set of data from a very big form, but it is like a "partial FormData".
I'm asking if exists a standard method to convert the content of an HTMLElement in an object like for the FormData.
PS: i can use also the data-attribute if necessary
Actually there is no standard quicky method to do this task.
The solution is iterate over inputs and selects:
<script>
let myObj = {};
let element = document.querySelector('[data-id="x"]');
element.querySelectorAll('input').forEach(el=> {
// check the type
// the property is : el.name
// the value must be : el.value for text/number/email...
// the value for the type="checkbox" is according to checked attribute
});
element.querySelectorAll('select').forEach(sel=> {
// if multiple choise => create an array of selected options
// if single => check the selected option's value
});
</script>
This is the code i've used (simplified)

Get all input values to javascript with the same id

I just want to get all different values using javascript with the same id.
Here is my input code:
<input type="text" id="full" name="full" value="2018-12-06">
<input type="text" id="full" name="full" value="2018-12-14">
<input type="text" id="full" name="full" value="2018-12-18">
When I alert the id of the inputs it show's the 2018-12-06 only. I want to disable the jquery datepicker but the 2018-12-06 is the only one read.
Here is my calendar.
and my javascript code:
var x = (document.getElementById('full').value);
var array = ["2018-12-25", "2019-01-01", x]
I want to disable all value with same id like the mention above,
IDs must be unique. You should add a class to each element and then use getElementsByClassName.
Because the method returns a nodelist to get each input value you need to iterate over it. For both these examples I've used map, but you might find a for/loop or forEach easier to use.
const full = document.getElementsByClassName('full');
const arr = [...full].map(input => input.value);
console.log(arr);
<input type="text" class="full" value="2018-12-06">
<input type="text" class="full" value="2018-12-14">
<input type="text" class="full" value="2018-12-18">
An alternative might be to use querySelectorAll. This uses CSS selectors so you can pinpoint elements by their attributes instead:
const full = document.querySelectorAll('[name="full"]');
const arr = [...full].map(input => input.value);
console.log(arr);
<input type="text" name="full" value="2018-12-06">
<input type="text" name="full" value="2018-12-14">
<input type="text" name="full" value="2018-12-18">
ID is used as an individual identifier. So it is illegal to use same Id for multiple elements. To get values of multiple elements use class instead of id.
You can use getElementsByClassName() function to read values of all elements with same class name
Alternative to getElementsByClassName() using jQuery
var l = $('.full').length;
//Initialize default array
var result = [];
for (i = 0; i < l; i++) {
//Push each element to the array
result.push($('.full').eq(i).val());
}
//print the array or use it for your further logic
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="full" value="2018-12-06">
<input type="text" class="full" value="2018-12-14">
<input type="text" class="full" value="2018-12-18">
You can't create an element with the same Id, If you want to get all different values from another element using javascript you can use ClassName
<input type="text" class="full" name="full" value="2018-12-06">
<input type="text" class="full" name="full" value="2018-12-14">
<input type="text" class="full" name="full" value="2018-12-18">
var x = document.getElementsByClassName('full');

Extract values from input fields and store in javascript array [duplicate]

This question already has answers here:
How to get all the values of input array element jquery [duplicate]
(3 answers)
Closed 5 years ago.
I have a webpage with a few input fields containing a value:
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">
I need Javascript/jQuery to extract these values and store them in an array like this:
var myArray = ["Apple", "Pear"];
Does anyone know of a way to do this?
Thanks!
You can use jQuery map() and get() to return array of values.
var myArray = $('input[type="text"]').map(function() {
return this.value;
}).get();
console.log(myArray)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">
jQuery solution.
var arr = [];
$('input').each(function(){
arr.push($(this).val());
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">
Or a pure js solution.
var elems = document.querySelectorAll('input[type="text"]'),
res = Array.from(elems).map(v => v.value);
console.log(res);
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">
Use document.querySelectorAll and Array#map:
var result = [].map.call(document.querySelectorAll('input'), function (e) {
return e.value
})
console.log(result)
<html>
<body>
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">
</body>
</html>
You have to loop through the input tags:
var data = [];
var inputs = document.getElementsByTagName('input');
for(var i=0; i< inputs.length; i++)
{
data.push(inputs[i].value);
}
console.log(data);
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">
If you use JQuery
var data = [];
$('input').each(function(){
data.push($(this).val());
});
console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">
Optimized JQuery:
var data = [];
$(":text").each(function(){ //only searches for input type="text"
data.push($(this).val());
});
console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">
UPDATE
I would strongly recommend you to use a common class in all your input elements and then loop through them like $('.the_class') as it is even more optimised.

How to get values of multiple input in one string by ".val()" using jquery?

I want to get the values of all input at once using one .val() function in jQuery.
$("#txt1").val();
$("#txt2").val();
$("#txt3").val();
Instead of this I want to write the below code
$("#txt1, #txt2, #txt3").val();
Use .map() to convert selected input to value of them and then use Array.prototype.join() to convert array result to string.
var values = $("#txt1, #txt2, #txt3").map(function(){
return this.value;
}).get().join(" ");
console.log(values)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt1" value="a" />
<input type="text" id="txt2" value="b" />
<input type="text" id="txt3" value="c" />
var arr= $("input").map(function(){
return $(this).val();
}).get();
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="1">
<input type="text" value="11">
<input type="text" value="11">
You need to loop through them try using .map()

Read HTML array using javascript or jQuery

I have array element in HTML
<input type="checkbox" value="Value1" name="model[settings][]">
<input type="checkbox" value="Value2" name="model[settings][]">
<input type="checkbox" value="Value3" name="model[settings][]">
I am reading all the HTML input, iterating it and building a hash in the javascript. But this will read the array element and only pick the last model[settings][] element.
var inputs = jQuery(" :input", "#elementID");
Is there a way in jQuery or JavaScript to read and build an array variable in javascript which then can be passed to controller ?
Thank You
If I understand you correctly, you are trying to iterate through all your input elements to get their value and store that as a JS object, correct?
If that's the case, I would add a unique ID to all my inputs, and then create an object with the structure { id : value }:
function getInputObject(sel) {
sel = $(sel);
var out = {};
sel.each(function() {
out[$(this).attr("id")] = $(this).val();
});
return out;
}
$(document).ready(function() {
console.log( getInputObject("input") );
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input1" value="value input 1" type="text" />
<input id="input2" value="value input 2" type="text" />
<input id="input3" value="value input 3" type="text" />

Categories