How to add multidimensional array to serialized POST data? - javascript

So, I am trying to POST form data to my API... and I wanted to add an array (multidimensional) to the post data, but i can't seem to figure it out.
Here's what i got so far:
let move_type = $("#move_type").text();
let loc_id = $("#loc_id").val()
// check a few vars first
let postvars;
postvars = $('#myForm input').serializeArray();
postvars.push({name: 'loc_id', value: loc_id}); //uncomment if you need to add vars in the postvars
postvars.push({name: 'move_type', value: move_type}); //uncomment if you need to add vars in the postvars
//loop through product ques
let prods_r = [];
$(".que_item").each(function(index){
let prod_id = $(this).find(".prod_id").text();
let title = $(this).find(".title").text();
let qty = $(this).find(".qty").val();
if(qty<1) {
showAlert("Please supply qty on all items in que. " + title);
return false;
}
prods_r[prod_id] = [];
prods_r[prod_id]["title"] = title;
prods_r[prod_id]["qty"] = qty;
})
postvars.push(prods_r);
When submitting this I get the variable for prods_r as "undefined" with no value.
I've also tried the following line to no avail
postvars.push({name: `prods_r`, value:prods_r });
I'm definitely missing something here ey?

You need to push all values to outer array else all values will get lost and it will return you empty array.
Demo Code :
$("form").on("submit", function(e) {
e.preventDefault()
let move_type = $("#move_type").text();
let loc_id = $("#loc_id").val()
let postvars;
postvars = $('#myForm input').serializeArray();
postvars.push({
name: 'loc_id',
value: loc_id
});
postvars.push({
name: 'move_type',
value: move_type
});
var dataa = new Array() //declare this
$(".que_item").each(function(index) {
let prod_id = $(this).find(".prod_id").text();
let title = $(this).find(".title").text();
let qty = $(this).find(".qty").val();
if (qty < 1) {
showAlert("Please supply qty on all items in que. " + title);
return false;
}
var prods_r = {}//create obj
//add value to it..
prods_r[prod_id] = {
"title": title,
"qty": qty
}
dataa.push(prods_r) //push in main array
})
postvars.push({
name: "prods_r",
value: dataa //passs it here
});
console.log(postvars)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="myForm">
<input tye="text" name="name" value="abc">
<input type="submit">
</form>
<div class="que_item">
<span class="prod_id">1</span>
<span class="title">Abcd</span>
<input tye="text" name="ded" class="qty" value="34">
</div>
<div class="que_item">
<span class="prod_id">2</span>
<span class="title">Abcd2</span>
<input tye="text" name="ded" class="qty" value="55">
</div>

Related

How can i get the data from localstorage and view in table using javascript and make a dropdown to sort the table

I have the following code that need to display the id,name and occupation. i can add to local storage but need to display it in table and sort based on name, id and occupation. any idea how can i do it using javascript. sample outputoutput
<!DOCTYPE html>
<html>
<title>Sorting Test</title>
<body>
<fieldset>
<legend>Add participant<legend>
<input id="userID" type="text">
<input id="userName" type="text">
<input id="userOccupation" type="text">
<button id="addbtn" type="button" >Add</button>
</fieldset>
<br>
<div id="displayOutput">
</div>
</body>
<script>
// get the userid, userName and UserOccupation
const userID = document.getElementById("userID");
const userName = document.getElementById("userName");
const userOccupation = document.getElementById("userOccupation");
const addbtn = document.getElementById("addbtn");
const displayOutput = document.getElementById("displayOutput");
//add user input to storage
addbtn.onclick = function(){
const id = userID.value;
const name = userName.value;
const occupation = userOccupation.value;
if(id && name && occupation)
{
let myObj = {
id,
name,
occupation
};
let myObj_serialized = JSON.stringify(myObj);
localStorage.setItem("myObj",myObj_serialized);
}
//view the stored information
for (let i=0; i < localStorage.length; i++)
{
const key = localStorage.key(i);
const value =localStorage.getItem(key);
var row = `<tr><td>${key}: ${value}<td><tr><br/>`;
displayOutput.innerHTML += row;
console.log(value);
}
};
</script>
</html>
You are overriding the stored item values everytime you call setItem. If you want to display a table, I suggest storing an array of objects. If you want to use local storage, Stringify the array before storing and parse it when you need to read it
var storeData = function(data) {
localStorage.setItem("tableData",JSON.stringify(data);
}
storeData([]);
var getData = function() {
return JSON.parse(localStorage.getItem("tableData"));
}
And call something like this to save data:
storeData(getData().push({id: id, name: name, occupation: occupation});
And then to display the data you can do:
var arr = getData();
arr.forEach(element) {
displayOutput.innerHtml += `
<tr>
<td>ID: ${element.id}</td>
<td>Name: ${element.name}</td>
<td>Occupation: ${element.occupation}</td>
</tr>`;
}
As for the sorting, you can call a sort function on the array on the onclick of the table's column header.

Don't append if string already contains OnChange

I have a javascript OnChange function on a column having textboxes which captures the name of each row in a column. I am appending all the names and storing in variable.
Now , suppose user clicks same textbox again , I don't want to append that name again.
var AppendedString = null;
function onChangeTest(textbox) {
AppendedString = AppendedString;
AppendedString = AppendedString + ';' + textbox.name;
// this gives null;txt_2_4;txt_2_6;txt_3_4;txt_2_4 and so on..and I don't want to append same name again , here it's txt_2_4
}
My Input text :
<input type="text" name="txt_<%=l_profileid %>_<%=l_processstepsequence%>" value="<%= l_comments%>" onfocus="this.oldvalue = this.value;" onchange="onChangeTest(this);this.oldvalue = this.value;">
Those rows seem to have unique names.
you can simply check if AppendedString already contains that name :
var AppendedString=''
function onChangeTest(textbox) {
if (!AppendedString.includes(textbox.name)) {
AppendedString += ';' + textbox.name;
}
}
Codepen Link
You can’t initialize AppendedString as null otherwise, the includes() method won’t be available
otherwise, you can give each row a unique ID, and store in an array IDs that already have been clicked by the user.
var AppendedString = '';
var clickedRows = [];
function onChangeTest(textbox) {
if (!clickedRows.includes(textbox.id)) {
AppendedString += ';' + textbox.name;
clickedRows.push(textbox.id)
}
}
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!(arr.indexOf(nowS) > -1)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
Somewhat similar to your need,
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!arr.includes(nowS)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
You can add flag your textboxes and ignore if it's clicked again. Like using jquery you can do something like this:
function onChangeTest(textbox) {
AppendedString = AppendedString;
if (!textbox.hasClass("clicked")){
AppendedString = AppendedString + ';' + textbox.name;
textbox.AddClass("clicked");
}
}

How can i add or update products and prices in my list?

Pretty new to javascript, i want to add and update my list but it doesn't work.
I tried adding following code but it didn't work
Product.prototype.addProduct = function() {
var elol = document.getElementById("lijst");
var nieuwNaam = document.createElement("li");
nieuwNaam.textContent= this.naam;
elol.appendChild(nieuwNaam);
var nieuwPrijs = document.createElement("li");
nieuwPrijs.textContent= this.prijs;
elol.appendChild(nieuwPrijs);
}
Product.prototype.getProducten = function() {
return this.naam + "(€ " + this.prijs +")";
}
This is the document i want wish would work propperly
<!DOCTYPE html>
<html>
<head>
<script src="oefwinkel.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
winkel.addProduct("Potlood", 10);
VulLijst();
var elBtn = document.getElementById("btn");
elBtn.onclick = VoegProductToe;
});
function VulLijst() {
var elol = document.getElementById("lijst");
var producten = winkel.getProducten("</li><li>");
if (producten.length > 0) {
elol.innerHTML = "<li>" + producten + "</li>";
} else {
elol.innerHTML = "";
}
}
function VoegProductToe() {
var naam = document.getElementById("txtNaam").value;
var prijs = document.getElementById("txtPrijs").value;
winkel.addProduct(naam, prijs);
VulLijst();
}
function Product(naam, prijs) {
this.naam = naam;
this.prijs = prijs;
}
</script>
</head>
<body>
<div><label for="txtNaam">Naam:</label>
<input type="text" id="txtNaam" /></div>
<div><label for="txtPrijs">Prijs:</label>
<input type="number" id="txtPrijs" /></div>
<input type="button" id="btn" value="Toevoegen/Updaten" />
<ol id="lijst">
</ol>
</body>
</html>
There is no list output how do i correct this?..
I really can't find the solution, what did i miss.. huh?
You had a few things missing,
The HTML code.
The winkel object was undefined.
The VulLijst function was doing nothing... because addProduct was taking care of this already.
You are relying on the instance fields (this.naam and this.prijs), but what you want to do is pass in method parameters (external variables).
As for updating, you will need to store a list of Products, clear the child elements of lijst, and re-add the items that represent the list.
Note: One thing I am confused about is why you named your class—that represents a list—Product, when it should really be an Inventory that allows you to ADD Product objects.
Code
// Uncaught ReferenceError: winkel is not defined
var winkel = new Product();
function Product(naam, prijs) {
this.naam = naam;
this.prijs = prijs;
}
Product.prototype.addProduct = function(naam, prijs) {
naam = naam || this.naam; // Default or instance field
prijs = prijs || this.prijs; // Default or instance field
console.log(naam, prijs);
var elol = document.getElementById("lijst");
var nieuwNaam = document.createElement("li");
nieuwNaam.textContent = naam;
elol.appendChild(nieuwNaam);
var nieuwPrijs = document.createElement("li");
nieuwPrijs.textContent = prijs;
elol.appendChild(nieuwPrijs);
}
Product.prototype.getProducten = function(naam, prijs) {
naam = naam || this.naam; // Default or instance field
prijs = prijs || this.prijs; // Default or instance field
return naam + " (€ " + prijs + ")";
}
document.addEventListener("DOMContentLoaded", function() {
winkel.addProduct("Potlood", 10); // Why are you adding a product to a product?
var elBtn = document.getElementById("btn");
elBtn.onclick = VoegProductToe;
});
function VoegProductToe() {
var naam = document.getElementById("txtNaam").value;
var prijs = document.getElementById("txtPrijs").value;
winkel.addProduct(naam, prijs);
}
label { font-weight: bold; }
<label>Product</label>
<input id="txtNaam" value="Something" />
<input id="txtPrijs"value="1.99" />
<button id="btn">Add</button>
<br/>
<ul id="lijst"></ul>
Explained
I will openly admit, I'm not 100% sure what you're trying to do, I assume that's due to a language barrier my side though, I'm not sure of the natural language that you use on a daily basis, i.e. some of the variable names seem unclear to me, but that's my problem, not yours! :)
Anyway, I used some guess work to figure out what you're trying to achieve, and I assumed that you're simply trying to have some sort of product list where each product has a name and a price attached to it?
You want to be able to add a product to the list, based on two input fields, then some button to add to/update that product list.
I've broken up the code into a couple of simple functions, with this solution you can add/remove as many functions, classes or whatever you want. In this answer you can clearly see that there's some render function, and some onUpdate function, I just went with these generic names for the sake of simplicity.
If you have any issues with this solution, please provide as much feedback as possible! I hope that it's been of some help one way or another.
// A simple product list.
const ProductList = () => {
const products = [];
let el = null;
// What you wish to return, aka an object...
return {
addProduct: (name, price) => {
products.push({
name: name,
price: price
});
onUpdate();
render(el, products);
},
setRoot: root => {
el = root;
},
// removeFromList, etc...
};
};
// A simple on update function.
const onUpdate = () => {
console.clear();
console.log('Update!');
};
// A 'simple' render function.
const render = (el, products) => {
if (el == null) return;
const template = obj => `<li>${obj.name} €${obj.price}</li>`;
let html = '';
products.forEach(product => html += template(product));
el.innerHTML = html;
};
// A function to dispatch some event(s).
const dispatchEvents = products => {
const btn = document.getElementById("btn");
const price = document.getElementById("price");
const name = document.getElementById("name");
// Just an example.
const isValid = () => {
if (price.value != '' && name.value != '') return true;
return false;
};
// Handle the on click event.
btn.onclick = () => {
if (isValid()) {
products.addProduct(name.value, price.value);
name.value = '';
price.value = '';
}
};
};
// A simple dom ready function.
const ready = () => {
const products = ProductList();
products.setRoot(document.getElementById("productList"));
products.addProduct('Demo', 10);
products.addProduct('Other', 19.99);
dispatchEvents(products);
};
document.addEventListener("DOMContentLoaded", ready);
<div>
<label for="name">name:</label>
<input type="text" id="name" />
</div>
<div>
<label for="price">Prijs:</label>
<input type="number" id="price" />
</div>
<input type="button" id="btn" value="Update" />
<ol id="productList">
</ol>

How to deal with value of text input created dynamically?

Here's a link
<form onsubmit="return false"></form>
<label for="quantity">qantity</label>
<select name="quantity">
<script>
for (var i = 1; i < 81; i++) {
document.write("<option value='"+i+"'>"+i+"</option>");
};
</script>
</select>
<button id="next">next</button>
<form id="itemform" onsubmit="return false"></form>
<script>
$('#next').click(function(){
var quantity = ($('select[name=quantity]').val());
$('#itemform').html("");
for (var i = 0; i < quantity; i++) {
$('#itemform').append("<label for='itemname"+i+"'>itemname</label><br><input type='text' name='itemname"+i+"' id='itemname"+i+"'><br><label for='itemprice"+i+"'>itemprice</label><br><input type='text' name='itemprice"+i+"' id='itemprice"+i+"'><br><br>");
};
$('#itemform').append("<button id='submit'>submit</button>");
});
$('#submit').click(function(){
var item = {};
$('input[type=text]').each(function(){
var key = $(this).attr('name');
var value = $(this).val();
item [key] = value;
});
console.log(item)
});
It creates text inputs as many as selected.
And then, it makes object like {itemname1 : "an awesome thing", ...}.
Creating input works very well but it doesn't make object.
It makes object input that doesn't created dynamically.
<form onsubmit="return false">
<input type="text" name="first">
<input type="text" name="second">
<input type="submit" id="submit">
</form>
<p id="res"></p>
<script>
$('#submit').click(function(){
var item = {};
$('input[type=text]').each(function(){
var key = $(this).attr('name');
var value = $(this).val();
item [key] = value;
});
console.log(item)
});
</script>
Why doesn't it work as I expected?
$('#submit') doesn't exist in your example. I replaced it with $('#itemform').submit() instead, and it seems to be logging a giant object. See the updated jfiddle here.
$('#itemform').submit(function(e){
e.preventDefault();
var item = {};
$('input[type=text]').each(function(){
var key = $(this).attr('name');
var value = $(this).val();
item [key] = value;
});
console.log(item)
});
Also, if you're looking at improving how items are stored, I updated the jsfiddle again here to show you how you can group items:
$(document).ready(function() {
$('#next').click(function(){
var quantity = ($('select[name=quantity]').val());
$('#itemform').html("");
for (var i = 0; i < quantity; i++) {
$('#itemform').append("<div class='item' data-item='" + i + "'><label for='itemname"+i+"'>itemname</label><br><input type='text' name='name' id='itemname"+i+"'><br><label for='itemprice"+i+"'>itemprice</label><br><input type='text' name='price' id='itemprice"+i+"'><br><br></div>");
};
$('#itemform').append("<button id='submit'>submit</button>");
});
$('#itemform').submit(function(e){
e.preventDefault();
var items = {};
$('#itemform div.item').each(function(){
var item = {};
$(this).find('input[type=text]').each(function() {
var key = $(this).attr('name');
var value = $(this).val();
item [key] = value;
});
items[$(this).data('item')] = item;
});
console.log(items)
});
});
This yields a much better object you can work with:
{
"0": {
"name": "item1name",
"price": "item1price"
},
"1": {
"name": "item2name",
"price": "item2price"
},
"2": {
"name": "item3 here",
"price": "item3 has a big price"
}
}
Don't attach your processing function to your form's submit button's click event. Instead, use the form's submit event.
Also, even though it doesn't make a difference syntax wise, for readability's sake, you might want to add a ";" after "console.log(item)".
$('#itemform').submit(function(){
var item = {};
$('input[type=text]').each(function(){
var key = $(this).attr('name');
var value = $(this).val();
item [key] = value;
});
console.log(item);
return false;
});
Also, no need for a onSubmit property on your form in your case, just return "false" with the processing function attached to your form's submit event.
<form id="itemform"></form>
See the updated fiddle here.

how to add the input values in an array

i just like to ask regarding adding data in a array. But the data which i wanted to put is from a table of input boxes.. Here's the code that i've been practicing to get data:
http://jsfiddle.net/yajeig/4Nr9m/69/
I have an add button that everytime I click that button, it will store data in my_data variable.
i want to produce an output in my variable something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}]
and if i would add another data again, it will add in that variable and it be something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"},
{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}]
the code that i have right now is really bad, so please help.
Currently my output:
1,4,6,4,1
You should be able to iterate over all of the textboxes using the following:
function add(e) {
var obj = {};
$('#addItem input[type="text"]')
.each(function(){obj[this.name] = this.value;});
myItems.push(obj);
}
Where myItems is a global container for your items and #addItem is your form.
Updated jsfiddle.
If you use a form and a submit button then you should be able to implement a non-JavaScript method to add your information so that the site will be accessible to people without JavaScript enabled.
Try this, sorry for modifying your form, but it works well:
HTML:
<form method="post" action="#" id="add_plank_form">
<p><label for="plank_number">Plank number</label>
<p><input type="text" name="plank_number" id="plank_number"/></p>
<p><label for="plank_width">Width</label>
<p><input type="text" name="plank_width" id="plank_width"/></p>
<p><label for="plank_length">Length</label>
<p><input type="text" name="plank_length" id="plank_length"/></p>
<p><label for="plank_thickness">Thickness</label>
<p><input type="text" name="plank_thickness" id="plank_thickness"/></p>
<p><label for="plank_quantity">Quantity</label>
<p><input type="text" name="plank_quantity" id="plank_quantity"/></p>
<p><input type="submit" value="Add"/>
</form>
<p id="add_plank_result"></p>
Javascript:
$(document).ready(function() {
var plank_data = Array();
$('#add_plank_form').submit(function() {
// Checking data
$('#add_plank_form input[type="text"]').each(function() {
if(isNaN(parseInt($(this).val()))) {
return false;
}
});
var added_data = Array();
added_data.push(parseInt($('#plank_number').val()));
added_data.push(parseInt($('#plank_width').val()));
added_data.push(parseInt($('#plank_length').val()));
added_data.push(parseInt($('#plank_thickness').val()));
added_data.push(parseInt($('#plank_quantity').val()));
$('#add_plank_form input[type="text"]').val('');
plank_data.push(added_data);
// alert(JSON.stringify(plank_data));
// compute L x W x F for each plank data
var computed_values = Array();
$('#add_plank_result').html('');
for(var i=0; i<plank_data.length; i++) {
computed_values.push(plank_data[i][1] * plank_data[i][2] * plank_data[i][3] / 12);
$('#add_plank_result').append('<input type="text" name="plank_add[]" value="' + computed_values[i] + '"/>');
}
return false;
});
});
Iterate through all keys, and add the values.
(code written from mind, not tested)
var added = { };
for (var i = 0; i < my_data.length; i ++) {
var json = my_data[i];
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (key in added) {
added[key] += json[key];
} else {
added[key] = json[key];
}
}
}
}
You can use the javascript array push function :
var data = [{plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}];
var to_add = [{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}];
data = data.concat(to_add);
Sorry I only glanced at the other solutions.
$(document).ready(function() {
var myData=[];
var myObject = {}
$("input").each(function() {
myObject[this.id]=this.value
});
alert(myObject["plank"])
myData.push(myObject)
});

Categories