Duplicate a form to work independently - javascript

I have a form which is currently doing a simple calculation. I have a button to duplicate the same form with an increment id and I need to do the calculations of the forms added independently.
var myJson = {
"platforms": [{
"name": "Sitecore",
"id": "Sitecore",
"tasktype": [{
"name": "Promobox",
"id": "Promobox",
"components": [{
"name": "Box 0",
"id": "box0",
"time": "20"
},
{
"name": "Box 1",
"id": "box1",
"time": "30"
}
]
},
{
"name": "Video",
"id": "Video",
"components": [{
"name": "Box 2",
"id": "box2",
"time": "25"
},
{
"name": "Box 3",
"id": "box3",
"time": "30"
}
]
}
]
},
{
"name": "Siab",
"id": "Siab",
"tasktype": [{
"name": "Newswire",
"id": "Newswire",
"components": [{
"name": "Box 4",
"id": "box5",
"time": "50"
},
{
"name": "Box 5",
"id": "box5",
"time": "40"
}
]
},
{
"name": "Task Type New",
"id": "Task Type New",
"components": [{
"name": "Box 6",
"id": "box6",
"time": "20"
},
{
"name": "Box 7",
"id": "box7",
"time": "100"
}
]
}
]
}
]
};
$.each(myJson.platforms, function(index, value) {
var platform_id;
var tasktype_id;
var component_id;
$("#platform").append('<option rel="' + index + '" value="' + value.id + '">' + value.name + '</option>');
$("#platform").change(function() {
$("#tasktype, #component").find("option:gt(0)").remove();
$("#tasktype").find("option:first").text("Loading...");
platform_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype, function(index1, value1) {
$("#tasktype").find("option:first").text("Select Task Type");
$("#tasktype").append('<option rel="' + index1 + '" value="' + value1.id + '">' + value1.name + '</option>');
});
});
$("#tasktype").change(function() {
$("#component").find("option:gt(0)").remove();
$("#component").find("option:first").text("Loading...");
tasktype_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype[tasktype_id].components, function(index2, value2) {
$("#component").find("option:first").text("Select Component");
$("#component").append('<option rel="' + index2 + '" value="' + value2.time + '">' + value2.name + '</option>');
});
});
});
$(document).ready(function() {
$('#calculate').click(function() {
let tr = $("<tr/>").appendTo("#data tbody");
$('#calc input, #calc select').each(function(index) {
var input = $(this);
$(tr).append('<td class=row-' + $(input).attr("id") + '>' + $(input).val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor * units;
$(tr).append('<td>' + total + '</td>');
});
});
$(document).ready(function() {
var calc_index = 0;
$("#addNew").click(function() {
calc_index++;
$("#calc").after($("#calc").clone().attr("id", "calc" + calc_index));
$("#calc" + calc_index).css("display", "inline");
$("#calc" + calc_index + " :input").each(function() {
$(this).attr("name", $(this).attr("name") + calc_index);
$(this).attr("id", $(this).attr("id") + calc_index);
});
});
});
$(document).ready(function() {
$('#calculate').click(function() {
let tr = $("<tr/>").appendTo("#data tbody");
$('#calc1 input, #calc1 select').each(function(index) {
var input = $(this);
$(tr).append('<td class=row-' + $(input).attr("id") + '>' + $(input).val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor * units;
$(tr).append('<td>' + total + '</td>');
});
});
$("#clear").click(function() {
location.reload();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Production Units Calculator</h2>
<div class="formset">
<form id="calc">
<label>Platform:</label>
<select id="platform" name="platform">
<option value="0">Select Platform</option>
</select>
<label>Task Type:</label>
<select id="tasktype" name="tasktype">
<option value="0">Select Task Type</option>
</select>
<label>Component:</label>
<select id="component" name="component">
<option value="0">Select Component</option>
</select>
<label>Units:</label>
<input name="units" id="units" type="number" min="0" placeholder="Input Units" />
<br />
</form>
</div>
<button id="calculate">Calculate</button>
<button id="addNew">Add New</button>
<button id="clear">Clear</button>
<table style="width:50%" id="data">
<thead>
<tr>
<th>Platform</th>
<th>Task Type</th>
<th>Component</th>
<th>Units</th>
<th>Time</th>
</tr>
</thead>
<tbody></tbody>
</table>
I was able to duplicate form with an increment ID however once the form is duplicated by clicking on add new , duplicated form doesn't work as the first one.

Please check this fiddle
You need to consider the change event for duplicate ID too.
$("#addNew").click(function() {
calc_index++;
$("#calc").after($("#calc").clone().attr("id", "calc" + calc_index));
$("#calc" + calc_index).css("display", "inline");
$("#calc" + calc_index + " :input").each(function() {
$(this).attr("name", $(this).attr("name") + calc_index);
$(this).attr("id", $(this).attr("id") + calc_index);
});
//TODO
$.each(myJson.platforms, function(index, value) {
var platform_id;
var tasktype_id;
var component_id;
pID = "#platform" + calc_index;
tID = "#tasktype" + calc_index;
cID = "#component" + calc_index;
$(pID).append('<option rel="' + index + '" value="' + value.id + '">' + value.name + '</option>');
$(pID).change(function() {
$(tID, cID).find("option:gt(0)").remove();
$(tID).find("option:first").text("Loading...");
platform_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype, function(index1, value1) {
$(tID).find("option:first").text("Select Task Type");
$(tID).append('<option rel="' + index1 + '" value="' + value1.id + '">' + value1.name + '</option>');
});
});
$(tID).change(function() {
$(cID).find("option:gt(0)").remove();
$(cID).find("option:first").text("Loading...");
tasktype_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype[tasktype_id].components, function(index2, value2) {
$(cID).find("option:first").text("Select Component");
$(cID).append('<option rel="' + index2 + '" value="' + value2.time + '">' + value2.name + '</option>');
});
});
});

Related

jquery json showing undefined with html table parsing

I want to show below json data on html table.how can i show to html table when i try to show with below code its show mae undefined
[
{
"Key": "data",
"Value": [
[
{
"Key": "created_time",
"Value": "2020-09-27T21:38:10+0000"
},
{
"Key": "message",
"Value": "My message"
},
{
"Key": "id",
"Value": "116312453556631_122404992947377"
}
]
},
{
"Key": "paging",
"Value": [
{
"Key": "cursors",
"Value": [
{
"Key": "before",
"Value": ""
},
{
"Key": "after",
"Value": ""
}
]
}
]
}
]
Below is my Code and its show me undefined
success: function (data) {
var items = '';
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='prtoducttd'>" + item.ID + "</td>"
+ "<td class='prtoducttd'>" + item.Message + "</td>"
+ "</tr>";
$('#tblPost tbody').append(rows);
});
}
what is generic method to parse the json and show it to html table?
Out put
id message created_time
116312453556631_122404992947377 "My message" "2020-09-27T21:38:10+0000"
Check if item.Key == "data". If it is, loop through item.Value to get the values for that row.
var data = [{
"Key": "data",
"Value": [{
"Key": "created_time",
"Value": "2020-09-27T21:38:10+0000"
},
{
"Key": "message",
"Value": "My message"
},
{
"Key": "id",
"Value": "116312453556631_122404992947377"
}
]
},
{
"Key": "paging",
"Value": [{
"Key": "cursors",
"Value": [{
"Key": "before",
"Value": ""
},
{
"Key": "after",
"Value": ""
}
]
}]
}
];
$.each(data, function(i, item) {
if (item.Key == "data") {
let id, message, created;
$.each(item.Value, function(j, obj) {
switch (obj.Key) {
case 'id':
id = obj.Value;
break;
case 'message':
message = obj.Value;
break;
case 'created_time':
created = obj.Value;
break;
}
});
debugger;
let rows = "<tr>" +
"<td class='prtoducttd'>" + id + "</td>" +
"<td class='prtoducttd'>" + message + "</td>" +
"<td class='prtoducttd'>" + created + "</td>" +
"</tr>";
$('#tblPost tbody').append(rows);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblPost">
<thead>
<tr>
<th>ID</th>
<th>Message</th>
<th>Created Time</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Make sure you're getting the data correctly first
For example, at item[0] see if the scope chain shows object available. Use the debugger and console to look through the data structure to follow the scope chain. Then write a loop once you've got the item and i correctly.
$.each(data, function (i, item) {
for (i = 0; i < item.Value.length; i++) {
let rows = "<tr>" +
"<td class='prtoducttd'>" + item.Value[i][2].Value + "</td>" +
"<td class='prtoducttd'>" + item.Value[i][1].Value + "</td>" +
"<td class='prtoducttd'>" + formatDate(new Date(item.Value[i][0].Value)) + "</td>" +
"</tr>";
$('#tblPost tbody').append(rows);
}
});

How to display nested JSON object in the form of table and rest JSON value as simple text

I want to display nested JSON objects.
This is what I have done so far:
orders = [
{ "custname": "Jack Smith", "mobile": "425361434", "location": "Sector 14", "slot": "12PM2PM", "value": 72.6, "items": [{ "prodcode": "PEP122", "quantity": 2 }, { "prodcode": "COK238", "quantity": 4 }] },
{ "custname": "Mary Gomes", "mobile": "723476123", "location": "Sector 22", "slot": "4PM6PM", "value": 130.60, "items": [{ "prodcode": "SUN677", "quantity": 2 }, { "prodcode": "LUX831", "quantity": 4 }, { "prodcode": "DET810", "quantity": 1 }] },
{ "custname": "Tim May", "mobile": "835099614", "location": "Pioneer Chowk", "slot": "Before 10AM", "value": 705, "items": [{ "prodcode": "GAR004", "quantity": 6 }, { "prodcode": "RB0277", "quantity": 3 }, { "prodcode": "MIR411", "quantity": 2 }] }
];
function showAllOrder() {
showtable();
}
function showtable() {
for (var i = 0; i < orders.length; i++) {
order = orders[i];
var str = "<div><div class='cell22' onclick=clicked(0)>Product</div>";
str = str + "<div class='cell22' onclick=clicked(1)>Qantity</div>";
var len = orders[i].items.length;
for (var j = 0; j < len; j++) {
for (var x = 0; x <)
//this value as simple text form above the table
var cost = ("Coustomer Name :" + order.custname);
var mob = (" Mobile :" + order.mobile);
var loc = (" Location :" + order.location);
var del = (" Delivery Slot :" + order.slot);
//this value in the form of table
var prod1 = "<div class='cell11'>" + orders[i].items[j].prodcode + "</div>";
var qty1 = "<div class='cell11'>" + orders[i].items[j].quantity + "</div>";
var row = "<div>" + cost + mob + loc + del + prod1 + qty1 + "</div>";
str = str + row;
}
}
var element = document.getElementById("mytable01");
element.innerHTML = str;
}

JSON dependent dynamic dropdown third level array error

I have three dropdowns which are depend on each other. Based on the selection of Dropdown A will have a list of results in Dropdown B, and based on the selection of Dropdown B will have a list of results in Dropdown C.
I can populate the first two dropdowns without a problem. However the last dropdown does shows me incorrect options.
$(function() {
var platforms;
var tasktypes;
var compos;
var jsonData;
$('#addnew').click(function(){
$('#dataset').clone().appendTo($('#newfield'));
});
$.getJSON('tasks.json', function(result) {
jsonData = result;
$.each(result, function(i, platform) {
platforms += "<option value='" +
platform.name +
"'>" +
platform.name +
"</option>";
});
$('#platform').html(platforms);
});
$("#platform").change(function (){
var idx = $("#platform").prop('selectedIndex');
var platforms = jsonData[idx].task;
tasktypes = "";
for (i = 0; i < platforms.length; i++) {
tasktypes += "<option value='" +
platforms[i].taskname +
"'>" +
platforms[i].taskname +
"</option>";
};
$('#taskname').html(tasktypes);
});
$("#taskname").change(function (){
var idc = $("#taskname").prop('selectedIndex');
var tasktypes = jsonData[idc].task[0].component;
compos = "";
for (i = 0; i < tasktypes.length; i++) {
compos += "<option value='" +
tasktypes[i].componentname +
"'>" +
tasktypes[i].componentname +
"</option>";
};
$('#components').html(compos);
});
});
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<button id="addnew">Add new</button>
<div id="dataset">
Platform:
<select id="platform">
</select>
Task Type:
<select id="taskname">
</select>
Component:
<select id="components">
</select>
Units:
<input type="number" min="0" />
</div>
<div id="newfield"></div>
<button id="calculate">Calculate</button>
<button id="clear">Clear</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
Json
[
{
"name": "Sitecore",
"value": "sitecore",
"task": [
{
"taskname": "promobox",
"component": [
{
"componentname": "A",
"time": "20"
},
{
"componentname": "B",
"time": "10"
}
]
},
{
"taskname": "video",
"component": [
{
"componentname": "C",
"time": "20"
},
{
"componentname": "D",
"time": "10"
}
]
}
]
},
{
"name": "Siab",
"value": "siab",
"task": [
{
"taskname": "promobox",
"component": [
{
"componentname": "E",
"time": "20"
},
{
"componentname": "F",
"time": "10"
}
]
},
{
"taskname": "newswire",
"component": [
{
"componentname": "G",
"time": "20"
},
{
"componentname": "H",
"time": "10"
}
]
},
{
"taskname": "video",
"component": [
{
"componentname": "I",
"time": "20"
},
{
"componentname": "J",
"time": "10"
}
]
}
]
}
]
First two dropdowns works fine. Once I select a platform from the first dropdown, second dropdown populates with the relevant tasknames. But once I select a taskname from the second dropdown, third dropdown does show irrelevant data. I can't figure out what's wrong I'm doing here.
I believe the major problem you have is jsonData = result during the ajax request. All ajax requests are asynchronous by default, hence, every data produced from it is mostly non-existent after the request completion. So your best bet will be to pass result to the HTML DOM object during the request.
$.getJSON('tasks.json', function(result) {
$('#platform').data('jsonData',result);//Assign Json data to data object of platform id
$.each(result, function(i, platform) {
platforms += "<option value='" +
platform.name +
"'>" +
platform.name +
"</option>";
});
$('#platform').html(platforms);
});

JSON & Dynamic jQuery Mobile Listview

I have a JSON file that contains an array of 3 objects.
When I want to display an object's attribute it display the name of it, for instance if I have an object car that has an attribute called name and has the value "FIAT" when I write car.name it displays " CAR.NAME " on the the listview instead of FIAT.
Here's my code.
$.getJSON("res/jsonFile/produits.json", function(products) {
$('#productList').empty();
$.each(products, function(i, product) {
$('#productList').append(productLink(product));
});
$('#productList').listview('refresh');
});
function productLink(product) {
var link="<li>" +
"<img src=product.pic>" +
"" +
"<h2>product.name</h2>" +
"<p>product.desc</p>" +
"<p>product.price</p>" +
"</li>";
return link;
}
and here's my JSON file
[
{
"name": "Coca Cola",
"desc": "Coca Cola",
"price": 10,
"qty": 100,
"pic": "img/coca cola.jpg"
},
{
"name": "Fanta",
"desc": "Fanta mini",
"price": 10,
"qty": 100,
"pic": "img/fanta.jpg"
},
{
"name": "Salade niçoise",
"desc": "Salade",
"price": 15,
"qty": 100,
"pic": "img/nicoise.jpg"
}
]
In your function you're printing the variable names, not their values. Use it like this instead:
function productLink(product) {
var link="<li>" +
"<img src=" + product.pic + ">" +
"<h2>" + product.name + "</h2>" +
"<p>" + product.desc + "</p>" +
"<p>" + product.price + "</p>" +
"</li>";
return link;
}

Fetching a json from jsp and displaing on javascript

I need to fetch the values from this JSON in my java script this is coming from jsp:
[{
"selectionName": "Select",
"subSelections": [{
"id": 4,
"subSelectionName": "Select",
"description": "Deepmala"
}
]
}, {
"selectionName": "week14",
"subSelections": [{
"id": 7,
"subSelectionName": "1",
"description": ""
}
]
}, {
"selectionName": "test",
"subSelections": [{
"id": 6,
"subSelectionName": "test",
"description": ""
}
]
}, {
"selectionName": "select",
"subSelections": [{
"id": 3,
"subSelectionName": "sub-select",
"description": "Created by Prakash"
}
]
}, {
"selectionName": "testcreate",
"subSelections": [{
"id": 1,
"subSelectionName": "testcreate",
"description": ""
}
]
}, {
"selectionName": "by htmlwidget",
"subSelections": [{
"id": 5,
"subSelectionName": "by htmlwidget",
"description": "created by html widget"
}
]
}
]
Any suggestions? I am tring to fetch it like this:
function getSelection() {
var options = "";
$.getJSON('../r3/selection.jsp').done(function(json) {
//alert(json.selectionName);
// alert(json.subSelections);
// options += '<option value="' + value. selectionId + '">' + value.selectionName + '</option>';
$.each(json.subSelections, function(index, value) {
options += '<option value="' + value. subSelectionName + '">' + value. description + '</option>';
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$(document.body).append(select);
}).fail(function (jqxhr, textStatus, error) {
alert(' fail json : '+error);
});
}
//alert(json.selectionName);
// alert(json.subSelections); inside the loop gives me undefined value.
Try this:
$.each(json, function (key, data) {
$.each(data.subSelections, function (index, values) {
options += '<option value="' + values.subSelectionName + '">' + values.description + '</option>';
});
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$('body').append(select);

Categories

Resources