JQuery - Get values from html array inputs - javascript

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];
}

Related

How to get multiple values from input field in jquery?

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>

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>

Get Input field array index in jquery

I have array of input field like this;
<input type="text" name="pname[283]" value="" class="input" />
<input type="text" name="pname[678]" value="" class="input" />
<input type="text" name="pname[876]" value="" class="input" />
<input type="text" name="pname[454]" value="" class="input" />
Now i want to get the array indexes of every field inside foreach loop something like this
$('.input').each(function(e) {
console.log('get array indexes'); eg: 283, 678, 876, 454
});
You can parse the name attribute manually.
$('.input').each(function() {
const name = $(this).prop('name');
console.log(name.slice(name.indexOf('[') + 1, -1));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="pname[283]" value="" class="input" />
<input type="text" name="pname[678]" value="" class="input" />
<input type="text" name="pname[876]" value="" class="input" />
<input type="text" name="pname[454]" value="" class="input" />

Value of parent input

From select name change[] val(), I would like to get input from it's parent input id champion[] with JQuery but I'm getting
'undefined' error
<div id="p_scents">
<p>
<label for="p_scnts">
<input type="text" id="champion[]" size="20" list="champions" value="" placeholder="Enter Champion's name">
<datalist id="champions"></datalist>
Add General Change<a></a>
Add Spell<a></a>
<a>
<p>
<select name="change[]" id="change[]" onchange="val()"></select>
<label for="var" readonly="true">
<input type="text" id="championSpell[]">
<br>
<textarea type="text" id="p_scnt" size="20" name="p_scnt_2" value="" placeholder="Enter Description"></textarea>
<select></select>
</label>
Add Change
Remove Spell</p></a>
</label>
</p>
</div>
var championName = $("#change").closest('input').val();
HTML
<select name="change[]" id="change[]" onchange="val(this)"></select>
Javascript
function val(elm) {
var championName = $(elm).closest("label").find("input").val();
alert('champion name is ' + championName);
}

Get value from radio button AND copy value using JQuery

I've looked all over, and can see many ways to get the value of a radio button, but not take it the next step and set the same value to a similar set of radio buttons. Copying text values works fine, just can't get the radio buttons to copy also.
EDIT:
I added the entire relevant html:
<div class="form-container">
<div class="form-titles">
<h4>Customer <span>Shipping</span> Information</h4>
</div>
<div id="fillout-form">
<label for="name"><span>*</span>Contact Name:</label>
<input type="text" id="name" name="name" maxlength="50" class="required" />
<label for="company"><span>*</span>Company Name:</label>
<input type="text" id="company" name="company" maxlength="50" class="required" />
<label for="land-line"><span>*</span>Primary Phone:</label>
<input type="text" id="land-line" name="land-line" maxlength="50" class="required" />
<label for="cell">Cell Phone:</label>
<input type="text" id="cell" name="cell" maxlength="50" />
<label for="email"><span>*</span>Email:</label>
<input type="email" id="email" name="email" maxlength="50" class="required" />
<label for="fax">Fax:</label>
<input type="text" id="fax" name="fax" maxlength="50" />
<label for="address"><span>*</span>Street Address:</label>
<input type="text" id="address" name="address" maxlength="50" class="required" />
<label for="address-2">Street Address 2:</label>
<input type="text" id="address-2" name="address-2" maxlength="50" />
<label for="city"><span>*</span>City:</label>
<input type="text" id="city" name="city" maxlength="50" class="required" />
<label for="state"><span>*</span>State or Province:</label>
<input type="text" id="state" name="state" maxlength="50" class="required" />
<label for="zip"><span>*</span>Zip / Postal Code:</label>
<input type="text" id="zip" name="zip" maxlength="50" class="required" />
</div>
<div id="vertical-radio">
<div id="radio-buttons">
<label for="country"><span>*</span>Country:</label>
<div id="multi-line-radio"><input type="radio" name="country" id="country" value="USA" class="required" checked >United States</div>
<div id="multi-line-radio"><input type="radio" name="country" id="country" value="Canada" >Canada</div>
</div>
</div>
<div class="form-container">
<div class="form-titles">
<h4>Customer <span>Billing</span> Information</h4>
<div class="same-address">
<input type="checkbox" name="same-address" value="same-address" id="copyCheck"><p>Same as Shipping Address?</p>
</div>
</div>
<div id="fillout-form">
<label for="name_2"><span>*</span>Contact Name:</label>
<input type="text" id="name_2" name="name_2" maxlength="50" class="required" />
<label for="company_2"><span>*</span>Company Name:</label>
<input type="text" id="company_2" name="company_2" maxlength="50" class="required" />
<label for="land-line_2"><span>*</span>Primary Phone:</label>
<input type="text" id="land-line_2" name="land-line_2" maxlength="50" class="required" />
<label for="cell_2">Cell Phone:</label>
<input type="text" id="cell_2" name="cell_2" maxlength="50" />
<label for="email_2"><span>*</span>Email:</label>
<input type="email" id="email_2" name="email_2" maxlength="50" class="required" />
<label for="fax_2">Fax:</label>
<input type="text" id="fax_2" name="fax_2" maxlength="50" />
<label for="PO-Box_2">PO-Box:</label>
<input type="text" id="PO-Box_2" name="PO-Box_2" maxlength="50" />
<label for="address_2">Street Address:</label>
<input type="text" id="address_2" name="address_2" maxlength="50" />
<label for="address-2_2">Street Address 2:</label>
<input type="text" id="address-2_2" name="address-2_2" maxlength="50" />
<label for="city_2"><span>*</span>City:</label>
<input type="text" id="city_2" name="city_2" maxlength="50" class="required" />
<label for="state_2"><span>*</span>State or Province:</label>
<input type="text" id="state_2" name="state_2" maxlength="50" class="required" />
<label for="zip_2"><span>*</span>Zip / Postal Code:</label>
<input type="text" id="zip_2" name="zip_2" maxlength="50" class="required" />
</div>
<div id="vertical-radio">
<div id="radio-buttons">
<div id="country_option_2">
<label for="country_2"><span>*</span>Country:</label>
<div id="multi-line-radio"><input type="radio" name="country_2" id="country_2" value="USA" class="required" checked >United States</div>
<div id="multi-line-radio"><input type="radio" name="country_2" id="country_2" value="Canada" >Canada</div>
</div>
</div>
</div>
And jQuery:
$(document).ready(function(){
$(function(){
$("#copyCheck").change(function() {
if ($("#copyCheck:checked").length > 0) {
bindGroups();
} else {
unbindGroups();
}
});
});
var bindGroups = function() {
$("input[id='name_2']").val($("input[id='name']").val());
$("input[id='company_2']").val($("input[id='company']").val());
$("input[id='land-line_2']").val($("input[id='land-line']").val());
$("input[id='cell_2']").val($("input[id='cell']").val());
$("input[id='email_2']").val($("input[id='email']").val());
$("input[id='fax_2']").val($("input[id='fax']").val());
$("input[id='address_2']").val($("input[id='address']").val());
$("input[id='address-2_2']").val($("input[id='address-2']").val());
$("input[id='city_2']").val($("input[id='city']").val());
$("input[id='state_2']").val($("input[id='state']").val());
$("input[id='zip_2']").val($("input[id='zip']").val());
$("input:radio[name=country_2]:checked").val($("input:radio[name=country]:checked").val());
$("input[id='name']").keyup(function() {
$("input[id='name_2']").val($(this).val());
});
$("input[id='company']").keyup(function() {
$("input[id='company_2']").val($(this).val());
});
$("input[id='land-line']").keyup(function() {
$("input[id='land-line_2']").val($(this).val());
});
$("input[id='cell']").keyup(function() {
$("input[id='cell_2']").val($(this).val());
});
$("input[id='email']").keyup(function() {
$("input[id='email_2']").val($(this).val());
});
$("input[id='fax']").keyup(function() {
$("input[id='fax_2']").val($(this).val());
});
$("input[id='address']").keyup(function() {
$("input[id='address_2']").val($(this).val());
});
$("input[id='address-2']").keyup(function() {
$("input[id='address-2_2']").val($(this).val());
});
$("input[id='city']").keyup(function() {
$("input[id='city_2']").val($(this).val());
});
$("input[id='state']").keyup(function() {
$("input[id='state_2']").val($(this).val());
});
$("input[id='zip']").keyup(function() {
$("input[id='zip_2']").val($(this).val());
});
};
var unbindGroups = function() {
$("input[id='name']").unbind("keyup");
$("input[id='company']").unbind("keyup");
$("input[id='land-line']").unbind("keyup");
$("input[id='cell']").unbind("keyup");
$("input[id='email']").unbind("keyup");
$("input[id='fax']").unbind("keyup");
$("input[id='address']").unbind("keyup");
$("input[id='address-2']").unbind("keyup");
$("input[id='city']").unbind("keyup");
$("input[id='state']").unbind("keyup");
$("input[id='zip']").unbind("keyup");
};
});
Close your input tags
for example
<input type="radio" name="country" value="Canada">
should be
<input type="radio" name="country" value="Canada"/>
IDs are unique
and exist once, and only once, in a particular document.
for example
<div id="radio-buttons">...</div><div id="radio-buttons">...</div>
should be something like
<div id="radio-buttons-1">...</div><div id="radio-buttons-2">...</div>
or
<div class="radio-buttons">...</div><div class="radio-buttons">...</div>
open your mind
There doesn't seem to be a need to handle each of these on an individual basis, you should think "how can i get those to copy here" not "lets copy this one and this one and this one..."
which would give you jquery that looks more like this:
var ship = $('.form-container').eq(0).find('input'),//first fields
bill = $('.form-container').eq(1).find('input').not('#copyCheck,#PO-Box_2');//second fields
$('#copyCheck').on('change', function () {
if ($(this).prop('checked')) { bindGroups(); }//checked:bind answers
else { unbindGroups(); }//!checked:remove answers
});
function brains(e,i) {//runs on bindgroups and on irt
var tc;
if (e.is('[type=radio]')) {//if radio
tc = e.prop('checked');//get checked
bill.eq(i).prop('checked',tc);//add checked to corresponding element
} else if(e.is('[type=text],[type=email]')) {//if text or email
tc = e.val();//get value
bill.eq(i).val(tc);//add value to corresponding element
}
}
function bindGroups() {//copy
ship.each(function(i){//for each input
brains($(this),i);//run brains
$(this).on('keyup change', function() {//on keyup or change
brains($(this),i);//run brains
});
});
}
function unbindGroups() {//clear the deck
ship.each(function(i){//for each input
if ($(this).is('[type=radio]')) {//if radio
bill.eq(i).prop('checked',false);//reset radio optional
} else if($(this).is('[type=text],[type=email]')) {//if text or email
bill.eq(i).val('');//empty text optional
}
}).unbind();//unbind actions
}
That way your not writing jquery for every element individually.
made a fiddle: http://jsfiddle.net/filever10/bC3mQ/

Categories