How to get multiple values from input field in jquery? - javascript

I want to get input field values which are in foreach loop using jquery . Here is the html structure
#foreach ($products as $product)
<div class = "form-row">
<input type="text" name="quantity" class="form-control quantity"value="{{$product->quantity }}">
<input type="text" name="price" class="form-control price"value="{{$product->price}}">
</div>
#endforeach
I'm trying to get value in this way
var quantity = $('.quantity').val();
var price= $('.price').val();
But In this way, I get only first-row value. How can get all rows value using jquery?

You have to loop through all the elements to get the values from them.
You can try jQuery's .map() and .get() to get all the values in an array.
Demo:
var quantityArr = $('.quantity').map(function(){
return +this.value;
}).get();
console.log(quantityArr);
// if you want the value comma separated then join the array
var quantityCommaSeperatedString = quantityArr.join(',');
console.log(quantityCommaSeperatedString);
var priceArr = $('.price').map(function(){
return +this.value;
}).get();
console.log(priceArr);
// if you want the value comma separated then join the array
var priceCommaSeperatedString = priceArr.join(',');
console.log(priceCommaSeperatedString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="quantity" class="form-control quantity"value="1">
<input type="text" name="price" class="form-control price"value="10">
<input type="text" name="quantity" class="form-control quantity"value="2">
<input type="text" name="price" class="form-control price"value="20">
<input type="text" name="quantity" class="form-control quantity"value="3">
<input type="text" name="price" class="form-control price"value="30">
Update: As mentioned in the comment: get values by row
$('.form-row').click(function(){
var quantity = $(this).find('.quantity').val();
console.log(quantity);
var price = $(this).find('.price').val();
console.log(price);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "form-row">
<input type="text" name="quantity" class="form-control quantity"value="1">
<input type="text" name="price" class="form-control price"value="10">
</div>
<div class = "form-row">
<input type="text" name="quantity" class="form-control quantity"value="2">
<input type="text" name="price" class="form-control price"value="20">
</div>
<div class = "form-row">
<input type="text" name="quantity" class="form-control quantity"value="3">
<input type="text" name="price" class="form-control price"value="30">
</div>

Related

How can generate numbers from given number and then populate in while loop

i'm trying to generate numbers from from_number value and then populate in a loop
Let's say that from_number value is 10
`
<label>
<input type="text" class="form-control"
id="from_number" placeholder="from_number"
autocomplete="off">
</label>
start php while.. I have 50 inputs with the same name ['list']
<label>
<input type="text" class="form-control" name="list"
placeholder="list" autocomplete="off">
</label>
`
end php
`
$('#from_number').blur(function () {
let begin = document.getElementById('from_number').value;
let arr = [];
let inputs = document.querySelectorAll('[name^="list"]');
for (let i = 0; i < inputs.length; i++) {
inputs[i].value = arr.push(begin++) + begin -1;
}
});
`
Thanks
DESIRED OUTPUT
`
<input type="text" class="form-control" name="list" value="10" autocomplete="off">
<input type="text" class="form-control" name="list" value="11" autocomplete="off">
<input type="text" class="form-control" name="list" value="12" autocomplete="off">
<input type="text" class="form-control" name="list" value="13" autocomplete="off">
<input type="text" class="form-control" name="list" value="14" autocomplete="off">
<input type="text" class="form-control" name="list" value="50" autocomplete="off">
`
The document.querySelectorAll() method returns a NodeList object container which can be iterated over as an array. The event listener in the following code fragment checks that the input value is numeric before converting it to an integer and iterating over the array of inputs.
const startValueElem = document.getElementById("from_number");
startValueElem.addEventListener("blur", (event) => {
if (!isNaN(event.target.value)) {
let value = parseInt(event.target.value);
Array.from(document.querySelectorAll('[name^="list"]')).forEach(el => {
el.value = value++;
});
}
});

Dynamic table with 2 columns based on array length

I've got an array with dynamic length for example :
(2) [" Corn starch 33.02%", " sugar 22.21%"]
second time it might be different size
(3) [" Corn starch 33.02%", " sugar 22.21%", " sea salt 20.27% ]"
Now I have table which I can fill the data from array, but only if array length matchs table row.
<div class="tab-pane" id="adv">
<div class="section-title">
<div class="row content">
<br /><br />
<div id="elo" class="col-lg-6 pt-6 pt-lg-2">
<div id="stylized" class="myform">
<form id="form" name="form" method="post" action="index.html">
<div class="column" name="details" id="co">
<label>ING name: </label>
<input
type="text"
name="ing1"
id="name1"
class="form-control input-md"
/>
<input
type="text"
name="ing2"
id="name2"
class="form-control input-md"
/>
<input
type="text"
name="ing3"
id="name3"
class="form-control input-md"
/>
<input
type="text"
name="ing4"
id="name4"
class="form-control input-md"
/>
<input
type="text"
name="ing5"
id="name5"
class="form-control input-md"
/>
<input
type="text"
name="ing6"
id="name6"
class="form-control input-md"
/>
<input
type="text"
name="ing7"
id="name7"
class="form-control input-md"
/>
<input
type="text"
name="ing8"
id="name8"
class="form-control input-md"
/>
<input
type="text"
name="ing9"
id="name9"
class="form-control input-md"
/>
<input
type="text"
name="ing10"
id="name10"
class="form-control input-md"
/>
<input
type="text"
name="ing11"
id="name11"
class="form-control input-md"
/>
<input
type="text"
name="ing12"
id="name12"
class="form-control input-md"
/>
<input
type="text"
name="ing13"
id="name13"
class="form-control input-md"
/>
</div>
<div class="column">
<label>Total %: </label>
<input
type="text"
name="value1"
id="value1"
class="form-control input-md"
/>
<input
type="text"
name="value2"
id="value2"
class="form-control input-md"
/>
<input
type="text"
name="value3"
id="value3"
class="form-control input-md"
/>
<input
type="text"
name="value4"
id="value4"
class="form-control input-md"
/>
<input
type="text"
name="value5"
id="value5"
class="form-control input-md"
/>
<input
type="text"
name="value6"
id="value6"
class="form-control input-md"
/>
<input
type="text"
name="value7"
id="value7"
class="form-control input-md"
/>
<input
type="text"
name="value8"
id="value8"
class="form-control input-md"
/>
<input
type="text"
name="value9"
id="value9"
class="form-control input-md"
/>
<input
type="text"
name="value10"
id="value10"
class="form-control input-md"
/>
<input
type="text"
name="value11"
id="value11"
class="form-control input-md"
/>
<input
type="text"
name="value12"
id="value12"
class="form-control input-md"
/>
<input
type="text"
name="value13"
id="value13"
class="form-control input-md"
/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
now I can question is it possible to build table based on array length with dynamic ID for every single input.
What I am expecting as a output if for example my array length is 10, then create table with 10 rows where i can fill data from array
With basic JavaScript:
const data = ['Corn starch 33.02%', 'sugar 22.21%', 'sea salt 20.27'];
// Storing the table element
const tableElement = document.querySelector('#myTable');
// Generated HTML
let generated = '';
// Iterate over the list
for(let i = 0; i < data.length; i++) {
let dat = data[i];
// Generating HTML with data
generated += `
<tr>
<td>
<input
type="text"
name="value${i+1}"
value="${dat}"
class="form-control input-md"
/>
</td>
</tr>`
}
// Appending it to the <table> element
tableElement.innerHTML = generated;
<form method='post' name='form'>
<table id="myTable">
</table>
</form>
This is just an "easy" way, the correct one is to use DOM which is more complex.
If I understood your question correctly then a simple foreach loop to iterate through the array combined with some basic HTML generation should suffice. The following will add a new row for every item in the array with an input element named like value1...value100 etc
<form method='post' name='form'>
<table>
<?php
$arr=array(
'Corn starch 33.02%',
'sugar 22.21%',
'sea salt 20.27'
);
foreach( $arr as $i => $item ){
printf('<tr><td><input type="text" name="value%d" value="%s" class="form-control input-md" /></td></tr>',($i+1),$item);
}
?>
</table>
</form>

JQuery - Get values from html array inputs

A user has the capacity to add as many items as possible through html inputs. The inputs look like;
<input class="form-control" name="part_number[]" number" type="text">
<input class="form-control" name="part_number[]" number" type="text">
<input class="form-control" name="part_number[]" number" type="text">
<input class="form-control item" name="description[]" type="text">
<input class="form-control item" name="description[]" type="text">
<input class="form-control item" name="description[]" type="text">
I would like to add the items to my database for storage.. How do i iternate through each input? part number and description belong to a single row.
function getdata() {
var partNumbers = [];
var descriptions = [];
$('[name="part_number[]"]').each(function() {
partNumbers.push(this.value);
})
$('[name="description[]"]').each(function() {
descriptions.push(this.value);
})
var data = {
partNumbers: partNumbers,
descriptions: descriptions
}
$('#output').val(JSON.stringify(data))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control" name="part_number[]" type="text" value="part number 1">
<input class="form-control" name="part_number[]" type="text" value="part number 2">
<input class="form-control" name="part_number[]" type="text" value="part number 3">
<br>
<input class="form-control item" name="description[]" type="text" value="description 1">
<input class="form-control item" name="description[]" type="text" value="description 2">
<input class="form-control item" name="description[]" type="text" value="description 3">
<hr>
<button type="button" onclick="getdata()">get data</button>
<textarea id="output" rows="10" cols="100" placeholder="output"></textarea>
If your inputs are within a form, you can use .serializeArray() and then .reduce() it to create an object which stores keys and array values for multiple input types like below. You can then submit this data to your server to then store in your database:
const data = $("#myform").serializeArray().reduce((acc, o) => {
if (o.name.slice(-2) === "[]") {
acc[o.name] = acc[o.name] || [];
acc[o.name].push(o.value);
} else {
acc[o.name] = o.value;
}
return acc;
}, {});
console.log(data); // data to POST
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input class="form-control" name="part_number[]" value="pn1" type="text">
<input class="form-control" name="part_number[]" value="pn2" type="text">
<input class="form-control" name="part_number[]" value="pn3" type="text">
<input class="form-control item" name="description[]" value="desc1" type="text">
<input class="form-control item" name="description[]" value="desc2" type="text">
<input class="form-control item" name="description[]" value="desc3" type="text">
<input class="form-control item" name="single_data" value="non-array data" type="text">
</form>
From your question, I understand that you want the description and part number in a row.
Please find my answer using .each function of jQuery.
The .each() function iterates through all the specified elements and it returns the index position of each element. Here I'm iterating through the part number, so I want to take the corresponding description, that is the description at the index position of part_number. To achieve this am using another jQuery selector :eq(). It will select the element at index n within the matched set.
$(".submit").on("click", function(){
let user_input = [];
$("input[name='part_number[]']").each(function(index){
user_input.push({
part_number: $(this).val(),
description: $(`.item:eq(${index})`).val()
});
});
console.log("final result = ", user_input);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control" name="part_number[]" placeholder="number" type="text">
<input class="form-control" name="part_number[]" placeholder="number" type="text">
<input class="form-control" name="part_number[]" placeholder="number" type="text">
<input class="form-control item" name="description[]" placeholder="description" type="text">
<input class="form-control item" name="description[]" placeholder="description" type="text">
<input class="form-control item" name="description[]" placeholder="description" type="text">
<button type="submit" class="submit"> Save</button>
I would rather fix the HTML than trying to fix the data afterwards.
You have items with the values descriptionand part_number, in order to group the data i would firstly group them visually in your HTML by adding a wrapper around each part_number + description pair:
<div class="item">
<input type="text" name="part_number[]" />
<input type="text" name="decription[]" />
</div>
After that we fix the input names' and add them to a group item:
<div class="item">
<input type="text" name="item[part_number]" />
<input type="text" name="item[decription]" />
</div>
To add multiple item elements in your form you need to add an ID to each item when adding it to your form:
<div class="item">
<input type="text" name="item[0][part_number]" />
<input type="text" name="item[0][decription]" />
</div>
<div class="item">
<input type="text" name="item[1][part_number]" />
<input type="text" name="item[1][decription]" />
</div>
When adding these values to your database you can then iterate over them like so: ( I'm just guessing you will use PHP)
foreach( $_POST['item'] as $item) {
$item['part_number'];
$item['description];
}

Calculate values of multiple fields and display for every row in Javascript

I have an invoice which is not a table but inside a div in html are some input fields. These fields are being created dynamically by clicking on a button.
<li><input type="text" id="cost[]" name="unit[]" value="<?php echo $val->unit ; ?>"> </li>
<li><input type="text" id="qty[]" name="rate[]" value="<?php echo $val->rate ; ?>"> </li>
<li><input type="text" id="price[]" name="total[]" value="<?php echo $val->total ; ?>"> </li>
Now I want to multiply unit with rate and display it in the total field.
My Javascript is
window.onkeyup=function() {
var str = document.getElementById("cost[]").value;
var str1 = document.getElementById("qty[]").value;
var price = parseFloat(str*str1);
document.getElementById("price[]").value = price;
}
The javascript above works fine but it works only for the first row. For the rest of the rows below the first row, it does not work. I want the calculation for all the rows. I have seen some of the answers but none of them works in my case.
Any help is welcome.
What I observe from your code is that you might be using same ids for multiple items.
The "id" attribute assigns a name to an element. This name must be unique in a document.
Though we have a workaround like:
document.querySelectorAll("[id='someID']");
to select all elements with same "id"s, your HTML will be invalid.
And this is why we have "class" instead. A class is a group of elements.
Though I have used "name" attribute.
May be what you are looking for:
window.onkeyup=function() {
var items = document.querySelectorAll(".item");
var itemsArray = Array.prototype.slice.call(items,0);
var unit, rate, total, net = 0;
itemsArray.forEach(function(el){
unit = el.querySelector('input[name="unit[]"]').value;
rate = el.querySelector('input[name="rate[]"]').value;
total = unit * rate;
el.querySelector('input[name="total[]"]').value = total;
net+=total;
});
document.getElementById('net').value=net;
}
<div class='item'>
<li><input type="text" name="unit[]" value=""> </li>
<li><input type="text" name="rate[]" value=""> </li>
<li><input type="text" name="total[]" value=""> </li>
</div>
<br><br>
<div class='item'>
<li><input type="text" name="unit[]" value=""> </li>
<li><input type="text" name="rate[]" value=""> </li>
<li><input type="text" name="total[]" value=""> </li>
</div>
</br></br>
<li><input id='net' type="text" name="net[]" value=""> </li>
As I've stated before, It's not recommended to keep multiple elements with the same id on your HTML. But if you want to keep things that way, then you can make use of document.querySelectorAll and iterate over the elements to sum their value and store it in the total:
window.onkeyup=function() {
var costs = document.querySelectorAll("input[id='cost[]'");
var qtys = document.querySelectorAll("input[id='qty[]'");
var price = 0;
for (var i = 0; i < costs.length; i++){
price += +costs[i].value + +qtys[i].value;
}
document.getElementById("price[]").value = price;
}
<input type="text" id="cost[]" name="unit[]" value="2">
<input type="text" id="qty[]" name="rate[]" value="4">
<br>
<input type="text" id="cost[]" name="unit[]" value="2">
<input type="text" id="qty[]" name="rate[]" value="4">
<br>
<input type="text" id="cost[]" name="unit[]" value="2">
<input type="text" id="qty[]" name="rate[]" value="4">
<br>
<input type="text" id="cost[]" name="unit[]" value="2">
<input type="text" id="qty[]" name="rate[]" value="4">
<input type="text" id="price[]" name="total[]" value="">
var invoices = document.querySelectorAll('.invoice')
var handleChange = function (foo, bar, total) {
let str = +foo.value || 0
let str2 = +bar.value || 0
total.value = parseFloat(str*str2)
}
invoices.forEach(function(invoice) {
var foo = invoice.querySelector('input[name=foo]')
var bar = invoice.querySelector('input[name=bar]')
var total = invoice.querySelector('input[name=total]')
foo.addEventListener('keyup', function() {
handleChange(foo, bar, total)
})
bar.addEventListener('keyup', function() {
handleChange(foo, bar, total)
})
})
<div class="invoice">
<input type="text" name="foo">
<input type="text" name="bar">
<input type="text" name="total">
</div>
<div class="invoice">
<input type="text" name="foo" value="">
<input type="text" name="bar" value="">
<input type="text" name="total">
</div>
<div class="invoice">
<input type="text" name="foo">
<input type="text" name="bar">
<input type="text" name="total">
</div>
<div class="invoice">
<input type="text" name="foo">
<input type="text" name="bar">
<input type="text" name="total">
</div>
<div class="invoice">
<input type="text" name="foo">
<input type="text" name="bar">
<input type="text" name="total">
</div>
Notice how i prepended a + to the parse of str & str2 this operator turns any String number into a Number
I recommend you do this because when querying the value of a input[type=text] - it will give you the value represented as a String...
This is fine when multiplying e.g '1'*'2'// = 2...
But, if you want to ADD two numbers together, your sum will be interpreted as concatenation e.g '2'+'2' // = '22'
It may also be smart to default your values to 0 if a value is not provided or a Alphabetic or special character is put into the input e.g 'hello'*'2' // = NaN
try
var str = +foo.value || 0;
var str1 = +bar.value || 0;
var price = parseFloat(str*str1);
Alternatively, make your input type="number" this will limit the user to only be able to input numbers.

javascript synchronize inputs with same name

I need to synchronize all inputs with same name.
I don't know inputs names.
Example:
<input type="text" placeholder="number" name="fields[340]" required="" value="">
<input type="text" placeholder="number" name="fields[340]" required="" value="">
So now I need to synchronize inputs values.
Problem is that I don't know input names. This is what I have so far.
var $inputs = $(":input");
$inputs.keyup(function() {
$inputs.val($(this).val());
});
Use 'input[name="' + this.name + '"]' selector to get the inputs with same name.
var $inputs = $(":input");
$inputs.on('input',function() {
$('input[name="' + this.name + '"]').val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" placeholder="number" name="fields[340]" required="" value="">
<input type="text" placeholder="number" name="fields[340]" required="" value="">
<br/>
<input type="text" placeholder="number" name="fields[341]" required="" value="">
<input type="text" placeholder="number" name="fields[341]" required="" value="">

Categories