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.
Related
I have the following
<input type="text" class="form-control" name="total1" id="total1">
<input type="text" class="form-control" name="total1" id="total2">
I already get these two values using javascript.
but I want to display the result in a span like below or a P tag
<span id="sum">0</span>
I tried the following...but i want it to be auto...meaning once the input field if there, total should also appear
<script type="text/javascript" language="javascript" charset="utf-8">
function output(){
var value1 = document.getElementById('value1').value;
var value2 = document.getElementById('value2').value;
document.getElementById('result').innerHTML = parseInt(value1) + parseInt(value2);
}
function updateTextInput(val) {
document.getElementById('value2').value=val;
}
</script>
If you want to display the result you can simply use
Javascript : document.getElementById("sum").innerText = SumOfTwoValues
Jquery : $("#sum").text(SumOfTwoValues);
Please make sure you add required validations for the Summation value before assigning it.
Well first of you need some way to call the function output.
Now there are a few problems regarding the Ids of the elements, you have id="total1" but you are trying to call getElementById('value1').
same goes for total2 and sum.
Last I would add || 0 after your .value so incase 1 of the input's haven't been filled, then it set to 0, so we can use it as a number.
function output() {
var value1 = document.getElementById('total1').value || 0;
var value2 = document.getElementById('total2').value || 0;
document.getElementById('sum').innerHTML = parseInt(value1) + parseInt(value2);
}
<input type="text" class="form-control" oninput="output()" name="total1" id="total1">
<input type="text" class="form-control" oninput="output()" name="total1" id="total2">
<span id="sum">0</span>
With vanilla javascript
function a()
{
var a1=document.querySelectorAll('input')
let sum=0;
for(let i=0;i<a1.length;i++)
sum+=Number(a1[i].value)
document.querySelector('#e').innerHTML=sum
}
<input type="text" class="form-control" name="total1" id="total1" onchange="a()">
<input type="text" class="form-control" name="total1" id="total2" onchange="a()">
<p id="e"></p>
Calculation in one line of Javascript.
function calc() {
document.querySelector('#sum').innerHTML = [...document.querySelectorAll('input')].reduce((acc, input) => acc + Number(input.value), 0);
}
<input type="text" class="form-control" name="total1" id="total1" onchange="calc()">
<input type="text" class="form-control" name="total1" id="total2" onchange="calc()">
<p id="sum"></p>
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()
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();
I try to get my tag by tag name and change thats value, can you help me to find why this not work?
var r_capacity=document.getElementsByName("capacity");
function expireOtherFildes(){r_capacity.value="";}
ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/>
capacity: <input type="text" name="capacity" value="xxx"/>
You need to use this:
var r_capacity=document.getElementsByName("capacity")[0];
document.getElementsByName("capacity") returns an nodeList.
The nodes can be accessed by index numbers.
var r_capacity=document.getElementsByName("capacity")[0];
function expireOtherFildes(){r_capacity.value="";}
ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/>
capacity: <input type="text" name="capacity" value="xxx"/>
document.getElementsByName returns array. You have access it by index.Refer below -
var r_capacity=document.getElementsByName("capacity");
function expireOtherFildes(){
r_capacity[0].value="";
}
ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/>
capacity: <input type="text" name="capacity" value="xxx"/>
document.getElementsByName() return an array of NodeList. You need to select the first index, or simply switch to document.getElementById()
var r_capacity=document.getElementsByName("capacity")[0];
//-^^^
console.log(r_capacity);
function expireOtherFildes(){r_capacity.value="";}
ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/>
capacity: <input type="text" name="capacity" value="xxx"/>
You need to use
var r_capacity = document.getElementsByName("capacity")[0];
because var r_capacity = document.getElementsByName("capacity"); it's returning a nodeList and you can access that taking use of the index which is 0:
var r_capacity = document.getElementsByName("capacity")[0];
console.log(r_capacity);
function expireOtherFildes() {
r_capacity.value = "";
}
ID:
<input type="text" name="id" class="textBox" onFocus="expireOtherFildes()" />capacity:
<input type="text" name="capacity" value="xxx" />
A better approach to do it would be to use querySelector(), this will prevent from getting a problem like you encountered:
var r_capacity = document.querySelector("input[name='capacity']");
console.log(r_capacity);
function expireOtherFildes() {
r_capacity.value = "";
}
ID:
<input type="text" name="id" class="textBox" onFocus="expireOtherFildes()" />capacity:
<input type="text" name="capacity" value="xxx" />
Suppose an entry is made in a textbox. Is it possible to retain the same entered text in a second text box? If so, how is this done?
<html>
<label>First</label>
<input type="text" name="n1" id="n1">
<label>Second</label>
<input type="text" name="n1" id="n1"/>
</html>
<script>
function sync()
{
var n1 = document.getElementById('n1');
var n2 = document.getElementById('n2');
n2.value = n1.value;
}
</script>
<input type="text" name="n1" id="n1" onkeyup="sync()">
<input type="text" name="n2" id="n2"/>
More efficiently it can be done as :
For the one who will see the post now should use best practices of javascript.
<script>
function sync(textbox)
{
document.getElementById('n2').value = textbox.value;
}
</script>
<input type="text" name="n1" id="n1" onkeyup="sync(this)">
<input type="text" name="n2" id="n2"/>
<html>
<script type="text/javascript">
function copy()
{
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
n2.value = n1.value;
}
</script>
<label>First</label><input type="text" name="n1" id="n1">
<label>Second</label><input type="text" name="n2" id="n2"/>
<input type="button" value="copy" onClick="copy();" />
</html>
Well, you have two textboxes with the same ID. An Id should be unique, so you should prbably change this.
To set the value from one text box to another a simple call to getElementById() should suffice:
document.getElementById("n1").value= document.getElementById("n2").value;
(assuming, of course you give your secodn text box an id of n2)
Tie this up to a button click to make it work.
This worked for me and it doesn't use JavaScript:
<form name="theform" action="something" method="something" />
<input type="text" name="input1" onkeypress="document.theform.input2.value = this.value" />
<input type="text" name="input2" />
</form>
I found the code here
Use event "oninput". This gives a more robust behavior. It will also trigger the copy function when you copy paste.
You can this way also used copy contents of one textbox to another
function populateSecondTextBox() {
document.getElementById('txtSecond').value = document.getElementById('txtFirst').value;
}
<label>Write Here :</label>
<input type="text" id="txtFirst" onkeyup="populateSecondTextBox();" />
<br>
<label>Will be copied here :</label>
<input type="text" id="txtSecond" />