How to fix "ReferenceError: index is not defined" problem - javascript

I try to connect my REST server with JavaScript app. Using ajax query I get proper JSON, but I cannot bind it to my HTML website. I use data-bind in HTML:
<tbody>
<tr >
<td> <input type="number" data-bind="value: index" name="index" readonly> </td>
<td> <input type="text" data-bind="value: name" name="name"required> </td>
<td> <input type="text" data-bind="value: surname" name="surname"required> </td>
<td> <input type="date" data-bind="value: birthdate" name="birthdate" min="1950-01-01" max="2050-01-01" required> </td>
<td><button type="button" >Edit</button></td>
</tr>
</tbody>
In .js file I have below code:
'use strict';
var URL = 'http://localhost:8000/'
$(document).ready(function(){
var StateViewModel = function () {
var self = this;
self.students = ko.observableArray();
$.ajax({
url: URL + 'students',
type: 'GET',
dataType: 'json',
accepts: {
contentType: 'application/json'
}
}).done(function(result) {
console.log(result)
ko.mapping.fromJS(result, self.students);
});
}
var model = new StateViewModel();
ko.applyBindings(model);
});
And I get "ReferenceError: index is not defined" error.
When I request my REST appI get below JSON:
[
{
"index": 127001,
"name": "John",
"surname": "Smith",
"birthdate": "1996-11-11"
},
{
"index": 127002,
"name": "Abcd",
"surname": "Xyz",
"birthdate": "1996-11-01"
}
]
And in ajax function .done result is:
0: Object { index: 127001, name: "John", surname: "Smith", … }
1: Object { index: 127002, name: "Abcd", surname: "Xyz", … }
What could be the reason of "ReferenceError: index is not defined" error?

Your JSON looks fine, and there's nothing wrong with using 3 arguments for your mapping.fromJS with an empty object as the "options" argument. My guess is that it's a context issue with which object your markup is attempting to bind to. If you're still at the root level view-model the binding will fail because "Index" doesn't exist at the root level. You need a foreach binding to nest into the "students" child object.
var URL = 'http://localhost:8000/';
var sampleData = [{
"index": 127001,
"name": "John",
"surname": "Smith",
"birthdate": "1996-11-11"
},
{
"index": 127002,
"name": "Abcd",
"surname": "Xyz",
"birthdate": "1996-11-01"
}
];
var StateViewModel = function() {
var self = this;
self.students = ko.observableArray();
setTimeout(function() {
//console.log(sampleData)
ko.mapping.fromJS(sampleData, {}, self.students);
}, 1000);
}
var model = new StateViewModel();
ko.applyBindings(model);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<table>
<tbody data-bind="foreach: students">
<tr>
<td> <input type="number" data-bind="value: index" name="index" readonly> </td>
<td> <input type="text" data-bind="value: name" name="name" required> </td>
<td> <input type="text" data-bind="value: surname" name="surname" required> </td>
<td> <input type="date" data-bind="value: birthdate" name="birthdate" min="1950-01-01" max="2050-01-01" required> </td>
<td><button type="button">Edit</button></td>
</tr>
</tbody>
</table>

Taken straight from the docs
The first time you fetch data you should do this
var viewModel = ko.mapping.fromJS(data);
Then every time data is received from the server after that
ko.mapping.fromJS(data, viewModel);

I also managed to solve my problem in this way:
'use strict';
var URL = 'http://localhost:8000/'
$(document).ready(function(){
console.log("Abc")
ko.applyBindings(new customerViewModel());
});
function customerViewModel() {
var self = this;
self.studentsList = ko.observableArray();
$.ajax({
type: 'GET',
url: URL + 'students',
contentType: "application/json",
dataType: "json",
success: function(data) {
console.log(data)
var observableData = ko.mapping.fromJS(data);
var array = observableData();
self.studentsList(array);
},
error:function(jq, st, error){
alert(error);
}
});
}
And using foreach
data-bind="foreach: studentsList"

Related

How to load JSON response on each rows input fields

I am novice in Programming and searching answer for the below problem in this site over days but couldn’t figure anything yet.
Firstly, A input form will prompt to the user, then the user will define how many rows there will be.
Then in the HTML table, each rows has 3 input fields(ID, Name, Number).
When a user gives an ID, the name and number of that ID will be placed in the next input fields of that row. For better understanding I am attaching an img.
demo_img.png
studentInfo.php page, Ajax response will set here:
<form class="" action="" method="POST">
<?php
$count = $_REQUEST["countID"]; //<--get the number from the user
for($i=1; $i<=$count; $i++){
?>
<tr>
<td>
<input type="number" name="id[]" class="id">
</td>
<td>
<input type="text" name="fname[]" class="fname">
</td>
<td>
<input type="number" name="num[]" class="num">
</td>
</tr>
<?php
}
?>
</form>
The Ajax portion:
$(".id").change(function(){
var sid = $(this).val();
$.ajax({
method: "GET",
url: "getData.php",
data: {sid: sid},
dataType: "json",
success: function(data, textStatus, jqXHR){
if(data.length == 0){
alert("No data found");
} else {
// I am stuck here. If I console.log(data) the JSON format coming from getData.php is showing like this: {name: 'JACKS DONUTS', num: '185'}
}
},
error: function(jqXHR, textStatus, errorThrown) {
//Show the error msg
}
});
});
Now, How do I set the result to the input fields.
Any suggestion in my code will be greatly appreciated. Thanks in advance.
Your requirement can be achieve by post an array of IDs to an URL e.g. getData.php using ajax.
['1001', '1002', '1003']
Then the getData.php will return an array of student data with ID as key.
{
"1001": {
"name": "Student A",
"number": 20
},
"1002": {
"name": "Student B",
"number": 21
},
"1003": {
"name": "Student C",
"number": 23
}
}
Once you retrieved the student data, try to look for the student data by using the input ID as key, if the data exists, append the data to the form.
if (data[inputId]) {
const studentData = data[inputId];
/* following methods will find input with class name and set the input value with given value */
setValue('name', studentData.name);
setValue('number', studentData.number);
}
Following is the SAMPLE by post the IDs to an API placeholder URL and SIMULATE the return data:
/* bind click event to buttons */
$(document).ready(function() {
$("#add-row").click(addRow);
$("#get-data").click(getData);
});
/* add extra row for input ID */
function addRow() {
$rowHtml = `
<tr class="student-data">
<td><input type="text" class="id" name="id[]" /></td>
<td><input type="text" class="name" /></td>
<td><input type="text" class="number" /></td>
</tr>
`;
$("#form-table").append($rowHtml);
}
/* get data when user submit */
function getData() {
const fieldset = $('#fieldset')
const message = $('#message')
const inputs = $(`input[name="id[]"]`)
/* get multiple ids as array where which by the user */
const ids = inputs.toArray().map(function(input) {
return input.value
})
/* store ids in a data object */
const dataToSubmit = {
ids: ids
}
/* url to post to submit the data e.g. "getData.php" */
/* following is just a demo url */
const url = "https://jsonplaceholder.typicode.com/posts"
$.ajax({
method: "POST",
url: url,
data: dataToSubmit,
dataType: "json",
beforeSend: function() {
/* disable the form when submitting */
fieldset.prop("disabled", true);
message.html('Getting data...');
},
success: function(data, textStatus, jqXHR) {
/* your data should return an array of objects with the key is the id */
/* e.g. {1001: {name: "Student A", number: 20}, 1002: {name: "Student B", number: 21},…} */
/* THIS IS NOT PART OF THE CODE! this is just a simulation of fetching the data */
data = JSON.parse(`{"1001":{"name":"Student A","number":20},"1002":{"name":"Student B","number":21},"1003":{"name":"Student C","number":23}}`);
/* fill the student data once retrieved data */
fillStudentData(data);
},
complete: function() {
/* enable back the form after form was submitted */
fieldset.prop("disabled", false);
message.html('');
}
});
}
function fillStudentData(data) {
$('.student-data').each(function() {
/* get the id by find the input with "id" class */
const inputId = $(this).children().find(".id")[0].value;
/* get student data using id key */
const studentData = data[inputId];
/* set the name and number if there is data found */
if (studentData) {
/* this function will find the inputs in "student-data" class and filled the input with value */
const setValue = (className, value) => {
$(this).children().find("." + className)[0].value = value;
};
setValue('name', studentData.name);
setValue('number', studentData.number);
}
})
}
<form style="display: flex;">
<fieldset id="fieldset">
<table id="form-table" border="1" cellpadding="10">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr class="student-data">
<td><input type="text" class="id" name="id[]" /></td>
<td><input type="text" class="name" /></td>
<td><input type="text" class="number" /></td>
</tr>
</tbody>
</table>
<span>Sample ID: 1001, 1002, 1003</span>
<button type="button" id="add-row">Add Row</button>
<button type="button" id="get-data">Get Data</button>
<span id="message"></span>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Knockout.js - passing parameters

There is a problem with passing parameter, when I press button, nothing is going and there are no errors in console
<tbody data-bind="foreach: hotels">
<tr>
<td data-bind="text: Id"></td>
<td data-bind="text: Name"></td>
<td data-bind="text: Address"></td>
<td>
<button data-bind="click: $root.eksportuj" > #Html.Text("Eksportuj") </button>
</td>
</tr>
and
self.eksportuj = function (obj, event) {
$.ajax({
ulr: "#Url.Action("eksport", "Controller")",
type: 'POST',
data: {'Id' : obj.Id},
success: function (result)
{
alert("True");
},
error: function()
{
alert("Error");
}
});
}
Maybe the problem is in non-enclosed button tag, or tbody tag
<button data-bind="click: $root.eksportuj" > #Html.Text("Eksportuj") </button>
Simle JSFiddle DEMO works as expected
JSFiddle DEMO code:
var viewModel = new function()
{
var self = this;
self.hotels = ko.observableArray([{
Id : "1",
Name : "N1",
Address : "A1"
},{
Id : "2",
Name : "N2",
Address : "A2"
}]);
self.eksportuj = function (obj, event) {
alert(obj.Id)
}
}
ko.applyBindings(viewModel)

How to update the edited item of knockout js observablearray in UI part?

How to update the knockout js observablearray in UI part..Initially Im editing a item and in update function i'm trying to update a particular item so im sending the current item object to service and getting the updated vales as response. Inside the response I need to update the observablearray as well the UI too.. I have tried some thing like this and its not working for me... please check in http://jsfiddle.net/up8rB/20/
<div data-bind="ifnot: Role()">
<label for="description">Description</label>
<input type="text" data-bind="value: Description" class="form-control" placeholder="Enter the description..." />
<button data-bind="click: $root.create"> Create</button>
</div>
<div data-bind="if: Role">
<label for="description">Description</label>
<input type="text" data-bind="value: Role().Description" class="form-control" placeholder="Enter the description..." />
<button data-bind="click: $root.update"> Save</button>
</div>
<table id="example1" class="table table-bordered table-striped" data-bind="visible: Roles().length > 0">
<thead>
<tr>
<th>RoleID</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody data-bind="foreach: Roles">
<tr>
<td data-bind="text: $data.RoleID"></td>
<td data-bind="text: $data.Description"></td>
<td>
<button data-bind="click: $root.edit" >Edit</button>
<button data-bind="click: $root.delete" >Delete</button>
</td>
</tr>
</tbody>
</table>
function RoleViewModel() {
var self = this;
self.RoleID = ko.observable("0");
self.Description = ko.observable().extend({
required: { message: 'Please supply description ..' }
});
var Role = {
RoleID: self.RoleID,
Description: self.Description
};
self.Role = ko.observable();
self.Roles = ko.observableArray();
$.ajax({
url: 'Service.svc/RoleCollection',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Roles(data); //Put the response in ObservableArray
}
});
self.edit = function (Role) {
self.Role(Role);
}
self.update = function () {
var Role = self.Role();
$.ajax({
url: '..service.svc/UpdateRole',
cache: false,
type: 'PUT',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Role),
success: function (data) {
for (var i = 0; i < self.Roles().length; i++) {
alert(self.Roles()[i].RoleID());
if (self.Roles()[i].RoleID() === data.RoleID) {
self.Role(self.Roles()[i]);
break;
}
}
}
})
}
var viewModel = new RoleViewModel();
ko.applyBindings(viewModel);
Your issue is that your are assigning items to your observable array that aren't themselves observable, so your UI is not updating when they change.
I did some renaming, as I found it confusing with so many things named 'Role', but the first change was your array setup:
var roles = [{
RoleID: ko.observable(1),
Description: ko.observable('First item')
}, {
RoleID: ko.observable(2),
Description: ko.observable('Second item')
}];
I also modified the update function:
self.update = function () {
var _Role = self.Role();
for (var i = 0; i < self.Roles().length; i++) {
if (self.Roles()[i].RoleID === _Role.RoleID) {
self.Roles()[i] = _Role();
break;
}
}
}
See the Updated Fiddle
Update:
Your json response should populate the observableArray correclty, but you may have an issue when setting it back after the update, try setting the properties rather than overwriting the element:
self.update = function () {
var _Role = self.Role();
for (var i = 0; i < self.Roles().length; i++) {
if (self.Roles()[i].RoleID === _Role.RoleID) {
self.Roles()[i].RoleID = _Role().RoleID;
self.Roles()[i].Description = _Role().Description;
break;
}
}
}
See the Updated Fiddle

Update UI after ajax response

I am new to knocokout.js so i have a table in which data is bind using ajax call.When user click on edit button row information is fill to a form which is on same page below the table.
after ajax call which update the data into database successfully , i am not able to show the changed value of particular object which is changed into table. If i refresh then its show new value .
Here is my html and js code .
<div id="body">
<h2>
Knockout CRUD Operations with ASP.Net Form App</h2>
<h3>
List of Products</h3>
<table id="products1">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Category
</th>
<th>
Price
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody data-bind="foreach: Products">
<tr>
<td data-bind="text: Id">
</td>
<td data-bind="text: Name">
</td>
<td data-bind="text: Category">
</td>
<td data-bind="text: formatCurrency(Price)">
</td>
<td>
<button data-bind="click: $root.edit">
Edit</button>
<button data-bind="click: $root.delete">
Delete</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
</td>
<td>
</td>
<td>
Total :
</td>
<td data-bind="text: formatCurrency($root.Total())">
</td>
<td>
</td>
</tr>
</tfoot>
</table>
<br />
<div style="border-top: solid 2px #282828; width: 430px; height: 10px">
</div>
<div data-bind="if: Product">
<div>
<h2>
Update Product</h2>
</div>
<div>
<label for="productId" data-bind="visible: false">
ID</label>
<label data-bind="text: Product().Id, visible: false">
</label>
</div>
<div>
<label for="name">
Name</label>
<input data-bind="value: Product().Name" type="text" title="Name" />
</div>
<div>
<label for="category">
Category</label>
<input data-bind="value: Product().Category" type="text" title="Category" />
</div>
<div>
<label for="price">
Price</label>
<input data-bind="value: Product().Price" type="text" title="Price" />
</div>
<br />
<div>
<button data-bind="click: $root.update">
Update</button>
<button data-bind="click: $root.cancel">
Cancel</button>
</div>
</div>
</div>
Code
function formatCurrency(value) {
return "$" + parseFloat(value).toFixed(2);
}
function ProductViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Id = ko.observable("");
self.Name = ko.observable("");
self.Price = ko.observable("");
self.Category = ko.observable("");
var Product = {
Id: self.Id,
Name: self.Name,
Price: self.Price,
Category: self.Category
};
self.Product = ko.observable();
self.Products = ko.observableArray(); // Contains the list of products
// Initialize the view-model
$.ajax({
url: 'SProduct.aspx/GetAllProducts',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
// debugger;
$.each(data.d, function (index, prd) {
self.Products.push(prd);
})
//Put the response in ObservableArray
}
});
// Calculate Total of Price After Initialization
self.Total = ko.computed(function () {
var sum = 0;
var arr = self.Products();
for (var i = 0; i < arr.length; i++) {
sum += arr[i].Price;
}
return sum;
});
// Edit product details
self.edit = function (Product) {
self.Product(Product);
}
// Update product details
self.update = function () {
var Product = self.Product();
$.ajax({
url: 'SProduct.aspx/Update',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: "{Product:" + ko.toJSON(Product) + "}",
success: function (data) {
console.log(data.d);
self.Product(null);
alert("Record Updated Successfully");
},
error: function (data) {
console.log(data);
}
})
}
// Cancel product details
self.cancel = function () {
self.Product(null);
}
}
$(document).ready(function () {
var viewModel = new ProductViewModel();
ko.applyBindings(viewModel);
});
and my webmethod which called by ajax request is as follow :
// to update product
[WebMethod]
public static testModel.Product Update(testModel.Product Product)
{
testEntities db = new testEntities();
var obj = db.Products.First(o => o.Id == Product.Id);
obj.Name = Product.Name;
obj.Price = Product.Price;
obj.Category = Product.Category;
db.SaveChanges();
return obj;
}
and JSON response of ajax call as follow
{"d":{"__type":"testModel.Product","Id":31,"Name":"12","Category":"12","Price":1350,"EntityState":2,"EntityKey":
{"EntitySetName":"Products","EntityContainerName":"testEntities","EntityKeyValues":
[{"Key":"Id","Value":31}],"IsTemporary":false}}}
Here's what's happening. Here: self.Products.push(prd) prd is just a plain javascript object with plain property values, nothing is observable. You're pushing the raw object onto the Products observableArray, which updates the DOM because Products was changed and KO is watching it. When you click 'edit', you set self.Product to that plain object and the KO updates the DOM with this object and its values because Product was changed and KO is watching it. So now your Product form below displays, you see the information, and it looks like you can edit the properties but KO won't update those property changes because KO isn't watching them. They're not observable. Change:
$.each(data.d, function (index, prd) {
//self.Products.push(prd);
self.Products.push({
Id: ko.observable(prd.Id),
Name: ko.observable(prd.Name),
Price: ko.observable(prd.Price),
Category: ko.observable(prd.Category)
});
});
General helpful tips
<div data-bind="if: Product">
This only evaluates once when you bind the viewModel to the DOM with ko.applyBindings. Since self.Product has an initial value of null KO removes this altogether.*Note: I was thinking of #if for some reason.
This works like the visible binding except when the value is false, the element and its children are removed from the DOM. So there is more DOM manipulation going on than necessary. You probably just want to hide this <div>
I would recommend changing this to:
<div data-bind="visible: Product">
Instead of this:
<input type="text" data-bind="text: Product().Name" />
<input type="text" data-bind="text: Product().Category" />
<input type="text" data-bind="text: Product().Price" />
Try this instead:
<div data-bind="with: Product">
<input type="text" data-bind="text: Name" />
<input type="text" data-bind="text: Category" />
<input type="text" data-bind="text: Price" />
</div>
Consider renaming self.Product to self.SelectedProduct to make it more clear what it is for.
I'm not sure what this is doing in the ViewModel:
//Declare observable which will be bind with UI
self.Id = ko.observable("");
self.Name = ko.observable("");
self.Price = ko.observable("");
self.Category = ko.observable("");
var Product = {
Id: self.Id,
Name: self.Name,
Price: self.Price,
Category: self.Category
};
You don't use them in the DOM. You were kind of on the right path with this though. Instead, before the ProductViewModel, create this:
function ProductModel(data) {
var self = this;
data = data || {};
self.Id = ko.observable(data.Id);
self.Name = ko.observable(data.Name);
self.Price = ko.observable(data.Price);
self.Category = ko.observable(data.Category);
}
Now instead of:
$.each(data.d, function (index, prd) {
self.Products.push({
Id: ko.observable(prd.Id),
Name: ko.observable(prd.Name),
Price: ko.observable(prd.Price),
Category: ko.observable(prd.Category)
});
});
We can just do this:
$.each(data.d, function (index, prd) {
self.Products.push(new ProductModel(prd));
});
Hopefully that will get you headed in the right direction.
There is something to change:
Replace
$.each(data.d, function (index, prd) {
self.Products.push(prd);
})
With:
$.each(data.d, function (index, prd) {
self.Products.push({
Id: ko.observable(prd.Id),
Name: ko.observable(prd.Name),
Price: ko.observable(prd.Price),
Category: ko.observable(prd.Category)
});
})
Use ko.observable to make your properties notify the view of its changes so that the view can update accordingly. This should work but not perfect because this is 2 way binding, so whenever you update the values in your div, the view model object is updated immediately and even if your ajax fails to update the data in backend, making the data out of synch between client side and server side.
For better solution. You need to have a look at protectedObservable
$.each(data.d, function (index, prd) {
self.Products.push({
Id: ko.protectedObservable(prd.Id),
Name: ko.protectedObservable(prd.Name),
Price: ko.protectedObservable(prd.Price),
Category: ko.protectedObservable(prd.Category)
});
})
Inside your self.update ajax success function, trigger a change:
success: function (data) {
var product =self.Product();
product.Id.commit();
product.Name.commit();
product.Price.commit();
product.Category.commit();
self.Product(null);
alert("Record Updated Successfully");
}
And revert if there is error:
error: function (data) {
product.Id.reset();
product.Name.reset();
product.Price.reset();
product.Category.reset();
}
Update:
Remember to change all the places with Product.Property to Product.Property() to get its property value . For example: arr[i].Price should be changed to arr[i].Price()
Add self.Products.push(data.d); to the update() functions success handler.
success: function (data) {
console.log(data.d);
self.Product(null);
self.Products.push(data.d);
alert("Record Updated Successfully");
},
You need to update the array so that it reflects in bound html.

Putting dynamic sets of fields in form into JSON with JavaScript

I have a form that has a dynamic number of rows. Each row has 3 fields, a hidden id, code, and exchange.
<form id="form_in_question">
<table>
<tr>
<td>0</td>
<td>
<input type="hidden" id="id[]" value="123" />
<input type="input" id="code[]" value="abc" />
</td>
<td>
<select id="exchange[]">
<!-- Options... -->
<select>
<td>
<tr>
<!-- unlimited rows... -->
</table>
</form>
I am trying to get an object that looks like:
data: {
"0": {
id: "123",
code: "abc",
exchange: "2"
},
"1": {
id: "124",
code: "bcd",
exchange: "4"
}
}
So I can pass it a JSON object via AJAX like:
$("#dialogEditor").dialog('option', 'buttons', {'Save' : function() {
/* Define variables */
var data = $("#form_in_question").serializeArray();
$.ajax({
url: 'ajax.codes.php',
dataType: 'json',
data: {
action: "update_codes",
entryId: entry,
data: data
},
type: 'POST',
success: function() {
ui.showMsg("Codes Updated");
}
});
This is what the JSON looks like that I am actually passing:
data[0][name] id[]
data[0][value]
data[1][name] code[]
data[1][value] zxc
data[2][name] exchange[]
data[2][value] 15
data[3][name] id[]
data[3][value]
data[4][name] code[]
data[4][value] BVA
data[5][name] exchange[]
data[5][value] 5
or the raw data:
action=update_codes&ResortId=12&data%5B0%5D%5Bname%5D=id%5B%5D&data%5B0%5D%5Bvalue%5D=&data%5B1%5D%5Bname%5D=code%5B%5D&data%5B1%5D%5Bvalue%5D=zxc&data%5B2%5D%5Bname%5D=exchange%5B%5D&data%5B2%5D%5Bvalue%5D=15&data%5B3%5D%5Bname%5D=id%5B%5D&data%5B3%5D%5Bvalue%5D=&data%5B4%5D%5Bname%5D=code%5B%5D&data%5B4%5D%5Bvalue%5D=BVA&data%5B5%5D%5Bname%5D=exchange%5B%5D&data%5B5%5D%5Bvalue%5D=5
I tried a method I found on SO but it didn't group the 3 fields together.
The following code should work:
var data = [];
var table = $("table").get()[0];
for (var i=0; i<table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
var inputData = {};
inputData["id"] = $("input[id^='id']", $(tableRow.cells[1])).val();
inputData["code"] = $("input[id^='code']", $(tableRow.cells[1])).val();
inputData["exchange"] = $("select[id^='exchange']",$(tableRow.cells[2])).val();
rowData[$(tableRow.cells[0]).text()] = inputData;
data.push(rowData);
}
console.log(JSON.stringify(data));

Categories

Resources