I want to make a subtotal for each products that I have. I already create the codes and it's working well, but the problem is if there are two or more products, the price will only change the first product, not the second and the rest. So, how to make it dynamically with the rest of the product? Here's my code.
function priceTotal(value) {
var grandTotal = 0;
$('.subtotal').each(function() {
var qty = value;
var price = parseInt($('.price').text());
var subTotal = value * price;
grandTotal = grandTotal + subTotal;
// document.getElementById("subtotal").innerText = "Rp. " + subTotal.toLocaleString('en');
$(this).text("Rp. " + subTotal.toLocaleString('en'));
});
// document.getElementById("grandtotal").innerText = "Rp. " + grandTotal.toLocaleString('en');
$('.grandtotal').text("Rp. " + grandTotal.toLocaleString('en'));
}
$('.increment-btn').click(function(e) {
e.preventDefault();
var incre_value = $(this).parents('.quantity').find('.qty-input').val();
var value = parseInt(incre_value, 10);
value = isNaN(value) ? 0 : value;
if (value < 100) {
value++;
$(this).parents('.quantity').find('.qty-input').val(value);
}
priceTotal(value);
});
$('.decrement-btn').click(function(e) {
e.preventDefault();
var decre_value = $(this).parents('.quantity').find('.qty-input').val();
var value = parseInt(decre_value, 10);
value = isNaN(value) ? 0 : value;
if (value > 1) {
value--;
$(this).parents('.quantity').find('.qty-input').val(value);
}
priceTotal(value);
});
<table class="table">
<thead class="bg-transparent">
<tr>
<th scope="col" class="text-center">Thumbnail</th>
<th scope="col" class="text-center">Brand</th>
<th scope="col" class="text-center">Product</th>
<th scope="col" class="text-center">Size</th>
<th scope="col" class="text-center">Price</th>
<th scope="col" class="text-center">Quantity</th>
<th scope="col" class="text-center">Subtotal</th>
<th scope="col" class="text-center">Actions</th>
</tr>
</thead>
#foreach($cartlists as $cartlist)
<tbody class="bg-transparent" class="checkout_cart">
<tr class="cartpage">
<td class="text-center"><img src="{{asset('uploads/products/' . $cartlist->product->productimage)}}" width="100px;" height="100px;" alt="Image"></td>
<td class="text-center">{{$cartlist->product->brand->name}}</td>
<td class="text-center">{{$cartlist->product->productname}}</td>
<td class="text-center">{{$cartlist->product->productsize}}</td>
<td class="text-center">Rp. <span class="price" data-price="{{$cartlist->product->productprice}}">{{ $cartlist->product->productprice}}</span></td>
<td class="cart-product-quantity text-center" width="132px">
<div class="input-group quantity">
<div class="input-group-prepend decrement-btn changeQuantity" style="cursor: pointer">
<span class="input-group-text">-</span>
</div>
<input type="text" class="qty-input form-control text-center" maxlength="2" value="1">
<div class="input-group-append increment-btn changeQuantity" style="cursor: pointer">
<span class="input-group-text">+</span>
</div>
</div>
</td>
<td class="text-center">
<span class="subtotal">Rp. {{ number_format($cartlist->product->productprice)}}</span>
</td>
<td class="text-center">
Delete
</td>
</tr>
</tbody>
#endforeach
</table>
</div>
<div class="text-left mt-3">
<h5 class="bold">Total: <span class="grandtotal"></span></h5>
<p>Delivery and discount will be calculated during the checkout process.</p>
</div>
Here's the result:
ID has to be unique, you have the same id="subtotal" in every row. Change it for class.
JS
function priceTotal(value) {
var grandTotal = 0;
$('.subtotal').each(function() {
// ^^
var qty = value;
var price = parseInt($("#price").text());
var subTotal = value * price;
grandTotal = grandTotal + subTotal;
$(this).text("Rp. " + subTotal.toLocaleString('en'));
// ^^^^^^^ $(this) instead of document.getElementByid
});
document.getElementById("grandtotal").innerText = "Rp. " + grandTotal.toLocaleString('en');
}
HTML
<td class="text-center">
<span class="subtotal">Rp. {{ number_format($cartlist->product->productprice)}}</span>
</td>
The same problem will be with other IDs in your foreach loop. There are #price and #qty-input.
Related
I have a Dynamically created HTML table, when page loads I am creating the first row having following columns ItemName,I Code,MRP,Price,UnitQty,Disc%,DiscAmt,Gst%,GstAmt and TotalAmt
ItemName is autocomplete field, So user is selecting item name by typeing and when user focus out I am populating some respective fields ,When user Types inside UnitQty field I am calculating some values and populating according to that in respective fields on keyup event all this is happening in HTML table
outside the tabel I have a Input Field SubTotal which is I am getting with Some calculation i.e price * UnitQty so for respective table row There is a Total Amt column where I have to populate (price * UnitQty) +GstAmt +DiscAmt but currently I am populating price * UnitQty I will do that later
What My issue is
So below is a subTotal Input field where I am populating price * UnitQty of each row so I am storing the values in global variable and then adding the current variable into that but when I type suppose 2 and price is 100 it equals to 200 then I am removing 2 and writing 2 at that time it is adding the previous 200 and current 300 and populating 500 I know this is because of keyup it is adding previous value also but that's not correct
There is no column for subtotal in HTML table that's why I am storing it in a variable
function format(number, decimals = 2) {
const fixed = parseFloat(number).toFixed(decimals);
const [float, dec] = fixed.split('.')
const intFormatted = (+float)
return intFormatted + (dec ? '.' + dec : '');
}
$(document).ready(function() {
var tableData = {};
var tabledata = {
"ALMOND CHBAR~2402": {
"itemName": "ALMOND CHBAR",
"itemCode": "2402",
"costPrice": 20.0,
"gstPercentage": 14.5,
"unitCode": "NOS",
"mrp": 30.0
},
"A BR SB EX~333": {
"itemName": "A BR SB EX",
"itemCode": "333",
"costPrice": 1.0,
"gstPercentage": 0.0,
"unitCode": "NOS",
"mrp": 1.0
}
}
populateData(tabledata)
function rowappend(tbody) {
const markup =
`<tr>
<td>
<input type="text" class="form-control commanChange" id="itemNametd" name="itemNametd">
</td>
<td><input type="text" name="itemCodetd" id="itemCodetd" class="form-control commantd" readonly="readonly" tabindex="-1"></td>
<td><input type="text" name="mrptd" id="mrptd" class="form-control commantd" readonly="readonly" tabindex="-1"></td>
<td><input type="tel" id="purRatetd" class="form-control commantd"name="purRatetd"></td>
<td>
<input type="tel" id="unitQtytd"class="form-control commanChange" name="unitQtytd">
</td>
<td>
<input type="tel" id="discPercentagetd"class="form-control commanChange" name="discPercentagetd" value="0.00">
</td>
<td><input type="text" name="discAmttd" id="discAmttd" class="form-control commantd" readonly="readonly" tabindex="-1"></td>
<td><input type="text" name="gstPercentagetd" id="gstPercentagetd" class="form-control commantd" readonly="readonly" tabindex="-1"></td>
<td><input type="text" name="gstAmttd" id="gstAmttd" class="form-control commantd" readonly="readonly" tabindex="-1"></td>
<td><input type="text" name="totalAmttd" id="totalAmttd" class="form-control commantd" readonly="readonly" tabindex="-1"></td>
<input type="hidden" name="unittd" id="unittd" class="form-control commantd">
<td style="background-color: white;border: 1px white"><i class="fas fa-times fa-2x remove-btn" ></i></td>
</tr>`
$(tbody).append(markup);
setTimeout(() => $("[name=itemNametd]", tbody).last().focus(), 100);
var autoCompleteData = Object.keys(tableData);
$("[name=itemNametd]", tbody).last().autocomplete({
source: autoCompleteData,
autoSelectFirst: true,
autoFocus: true
}).data('tableData', tableData);
}
function getValues(row) {
const search = ($('[name=itemNametd]', row).val()).toString()
var data = $('[name=itemNametd]', row).data('tableData');
const value = data[search];
if (value) {
CostPrice = value.costPrice;
$(row).find("[name=itemCodetd]").val(value.itemCode);
$(row).find("[name=mrptd]").val(format(value.mrp));
$(row).find("[name=purRatetd]").val(format(CostPrice));
$(row).find("[name=unittd]").val(value.unitCode);
$(row).find("[name=gstPercentagetd]").val(value.gstPercentage);
$("[name=purRatetd]").focus();
}
}
$(document).on("keyup", "[name=purRatetd]", function(e) {
const row = e.target.parentElement.parentElement
var unitQuantity = $(row).find("[name=unitQtytd]").val();
var purchaseRate = $(row).find("[name=purRatetd]").val();
var mrp = $(row).find("[name=mrptd]").val();
totalAmount = (parseFloat(unitQuantity) * parseFloat(purchaseRate)) || 0;
$(row).find("[name=totalAmttd]").val(format(totalAmount));
});
var subTotalAmt = 0;
$(document).on("keyup", "[name=unitQtytd]", function(e) {
const row = e.target.parentElement.parentElement
unitQuantity = $(row).find("[name=unitQtytd]").val();
purchaseRate = $(row).find("[name=purRatetd]").val();
mrp = $(row).find("[name=mrptd]").val();
totalAmount = (parseFloat(unitQuantity) * parseFloat(purchaseRate)) || 0;
subTotalAmt += totalAmount || 0
$(row).find("[name=totalAmttd]").val(format(totalAmount));
$("#subTotalInput").val(format(subTotalAmt));
});
document.addEventListener("keydown", function(e) {
const row = event.target.parentElement.parentElement
var keycode = event.keyCode || event.which;
if (keycode == '13') {
if (!$(event.target).val()) {
e.preventDefault();
return;
}
const row = e.target.parentElement.parentElement
if (event.target.matches('[name=discPercentagetd]')) {
if ($(row).parent().find('tr').length - $(row).index() === 1) {
rowappend(event.target.parentElement.parentElement.parentElement)
}
}
}
});
$(document).on("focusout", "[name=itemNametd]", function(e) {
const row = e.target.parentElement.parentElement
getValues(e.target.parentElement.parentElement)
});
function populateData(data) {
tableData = Object.assign({}, data);
var autoCompleteData = Object.keys(data);
rowappend($('tbody', '#tableInvoice'));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="row tableGrn" id="commonDvScroll">
<table class="table table-bordered" id="tableInvoice">
<thead>
<tr>
<th id="itemNameth" class="commanth">Item Name</th>
<th id="itemCodeth" class="commanth">I Code</th>
<th id="mrpth" class="commanth">MRP</th>
<th id="purRateth" class="commanth">Price</th>
<th id="unitQtyth" class="commanth">Unit Qty</th>
<th id="discPercentageth" class="commanth">Disc %</th>
<th id="discAmtth" class="commanth">Disc Amt</th>
<th id="gstPercentageth" class="commanth">GST %</th>
<th id="gstAmtth" class="commanth">GST Amt</th>
<th id="totalAmtth" class="commanth">Total Amt</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="form-row">
<div class="form-group col-xs-6 col-sm-6 col-md-6 col-lg-2">
<label for="subTotalInput">Sub Total</label>
<div class="input-group">
<input type="tel" class="form-control" aria-label="Text input with dropdown button" name="subTotalInput" id="subTotalInput" readonly="readonly" tabindex="-1">
</div>
</div>
</div>
Note-: Please don't get confused by TotalAmt column that one is for other usage which I will do by adding all the amounts
For now I have been stuck in calculating subTotal row wise and populate in a Input field
On press of enter at Disc% it will create a new row
Please replace your code with below code
$(document).on("keyup", "[name=purRatetd],[name=unitQtytd]", function(e) {
var unitQuantity = $(this).closest('tr').find("[name=unitQtytd]").val();
var purchaseRate = $(this).closest('tr').find("[name=purRatetd]").val();
var unitQuantity = unitQuantity ? unitQuantity : 1;
var mrp = $(this).closest('tr').find("[name=mrptd]").val();
totalAmount = (parseFloat(unitQuantity) * parseFloat(purchaseRate));
$(this).closest('tr').find("[name=totalAmttd]").val(totalAmount);
var subTotal = 0;
$("[name=totalAmttd]").each(function(){
var curVal = parseFloat($(this).val());
if(curVal){
subTotal = curVal + subTotal;
}
});
$("#subTotalInput").val(subTotal);
});
N:B - you are using id in input fields which will repeat again and again after apending so avoid using id and name...In entire code you can use class instead of name or id......class name can be same but id and name can't be same in multiple fields
I am unable to send the value of javascript variale 'userResults' to .html.
I want to display the contents of the form in tabular form.
Can you tell me a workaround for this?
This is in index.html
<form onSubmit="App.retrieveTransaction();" class="form2">
<h1 class="text-center">Retrieve transactions</h1>
<div class="form-group">
<label for="enterregnoselect">Reg No:</label><input id ="enterregnoselect" class="form-control" type ="text" required/>
</div>
<button type="submit" class="btn btn-primary" >Retrieve</button>
<hr />
<table class="table">
<thead>
<tr>
<th scope="col">Date</th>
<th scope="col">Name</th>
<th scope="col">Item</th>
<th scope="col">Credit</th>
<th scope="col">Debit</th>
<th scope="col">Price</th>
<th scope="col">Qty</th>
</tr>
</thead>
<tbody id="userResults">
</tbody>
</table>
<hr/>
</form>
This is the retrieveTransaction function in app.js called on submitting the form in index.html
retrieveTransaction: function() {
var transactionInstance;
var enteredregno = $('#enterregnoselect').val();
// var enteredregno = "0015/55";
App.contracts.Payment.deployed().then(function(instance) {
transactionInstance = instance;
return transactionInstance.transactionCount();
}).then(function(transactionCount) {
var userResults = $("#userResults");
userResults.empty();
for (var i = 1; i <= transactionCount; i++) {
transactionInstance.transactions(i).then(function(transaction) {
var date = transaction[0];
var regno = transaction[1];
var name = transaction[2];
var item = transaction[3];
var credit = transaction[4];
var debit = transaction[5];
var price = transaction[6];
var qty = transaction[7];
if(enteredregno == regno) {
var userTemplate = "<tr><th>" + date + "</th><td>" + name + "</td><td>" + item + "</td></tr>" + credit + "</th><td>" + debit + "</td><td>" + price + "</td></tr>" + qty + "</td></tr>";
userResults.append(userTemplate);
}
});
}
});
I'm trying to post data to a Controller from an MVC View and I'm having problems. The code is as follows:
<div id="no-more-tables">
<table id="CarteraClients" style="width: 100%;">
<thead>
<tr>
<th scope="col" id="col1" width="55%">Cliente</th>
<th scope="col" id="col2">Semana 1 </th>
<th scope="col" id="col2">Semana 2 </th>
<th scope="col" id="col2">Semana 3 </th>
<th scope="col" id="col2">Semana 4 </th>
<th scope="col" id="col2">Semana 5 </th>
</tr>
</thead>
<tbody>
#{
if (Model.Count() == 0)
{
<tr>
<th colspan="4" class="error text-center">
<small class="error">No hay elementos coincidentes.</small></th>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td data-title="Razon Social">
#Html.DisplayFor(modelItem =>
item.razon_social)
</td>
<td data-title="Semana 1" id="Semana1"
class="row1">#Html.CheckBox("chkSemana1", false)</td>
<td data-title="Semana 2" id="Semana2"
class="row1">#Html.CheckBox("chkSemana2", false)</td>
<td data-title="Semana 3" id="Semana3"
class="row1">#Html.CheckBox("chkSemana3", false)</td>
<td data-title="Semana 4" id="Semana4"
class="row1">#Html.CheckBox("chkSemana4", false)</td>
<td data-title="Semana 5" id="Semana5"
class="row1">#Html.CheckBox("chkSemana5", false)</td>
</tr>
}
}
}
</tbody>
</table>
<button type="button" class="small" onclick="llenardata()"><img
src="~/Content/img/magnifying-glass-8x.png" alt="Buscar" width="16"
height="16" /> Guardar cartera</button>
</div>
The script that I'm using to generate the structure to send via json:
<script type="text/javascript">
function llenardata() {
var cant = 0;
var tabla = document.getElementById("CarteraClients");
var rowLength =
document.getElementById("CarteraClients").rows[0].cells.length;
var tablaresultados = [];
for (i = 0; i < tabla.rows.length; i++) {
var ocells = tabla.rows.item(i).cells;
var cellLength = ocells.length;
var cliente = ocells.item(0).innerText;
var semana1 = ocells.item(1).innerText;
var semana2 = ocells.item(2).innerText;
var semana3 = ocells.item(3).innerText;
var semana4 = ocells.item(4).innerText;
var semana5 = ocells.item(5).innerText;
tablaresultados.push(cliente);
//tablaresultados.push(semana1);
//tablaresultados.push(semana2);
//tablaresultados.push(semana3);
//tablaresultados.push(semana4);
//tablaresultados.push(semana5);
}
console.log(tablaresultados);
$.ajax({
url: url("IngresoProyeccion") + 'GuardarCarteraCliente',
data:
'IdUser=' + delegado +
'&Ano=' + anyos +
'&Mes=' + meses +
'&Oportunidad= Levantamiento de Oportunidades'+
'&Cartera='+tablaresultados,
dataType: 'json',
type: 'POST',
}).success(function (html) {
DesbloquearPantalla();
$("#divReporte").html(html);
//$("body").animate({ scrollTop: $(document).height() },
'fast');
});
}
</script>
But it doesn't take the values of the checkbox on semana1, semana2, semana3, semana4, semana5 in the var tablaresultados.
I need help to resolve this problem. Thanks.
In JavaScript hidden field value is stored.
But when clicked on next page hidden field is null it doesn't have values from previous page.
Why is it not loading previous values in next page?
How to load previous value in hidden field??
function AddRemoveCustomer(id) {
//$(".checkBoxClass").click(function (e) {
alert('in main function');
alert(id);
var CustomerIDArray = [];
var hidCID = document.getElementById("hfCustomerID");
if (hidCID != null && hidCID != 'undefined') {
var CustID = hidCID.value;
CustomerIDArray = CustID.split("|");
var currentCheckboxValue = id;
var index = CustomerIDArray.indexOf(currentCheckboxValue);
alert('index value:' + index);
debugger;
if (index == 0) {
alert('if');
CustomerIDArray.push(currentCheckboxValue);
alert('pushed value:' + CustomerIDArray);
} else {
alert('else');
var a = CustomerIDArray.splice(index, 1);
alert("a" + a);
}
hidCID.value = CustomerIDArray.join("|");
alert('Final' + hidCID.value);
} else {
alert('undefined');
}
//});
}
<table id="tblEmailScheduler" class="table-bordered col-offset-12">
<thead>
<tr class="label-primary">
<th style="padding:5px 15px;">
First Name
</th>
<th style="padding:5px 15px;">
Last Name
</th>
<th style="padding:5px 15px;">
Email ID
</th>
<th style="padding:5px 15px;">
Customer Type
</th>
<th style="padding:5px 15px;">
Customer Designation #Html.DropDownList("CustomerDesignation", new SelectList(ViewBag.SelectAllCustomerDesignationDDL, "Value", "Text"), new { id = "CustomerDesignationDDL" , name = "CustomerDesignationDDL" })
</th>
<th style="padding:5px 15px;">
Select All
<div class="checkbox control-group">
<label><input type="checkbox" id="cbSelectAll" /></label>
</div>
</th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="2">
EmailTemplate : #Html.DropDownList("EmailSubject", new SelectList(ViewBag.SelectAllEmailTemplateDDL, "Value", "Text"), new { id = "SelectAllEmailTemplateDDL" })
</th>
<th colspan="2">
Set Date And Time:
<input type="text" class="from-date-picker" readonly="readonly" />
</th>
<th colspan="2">
<input type="submit" value="Schedule" id="btnSubmit" class="btn btn-default" />
</th>
<td>
</td>
</tr>
</tfoot>
#foreach (var item in Model) {
<tr style="text-align:center">
<td id="tblFirstName">
#item.FirstName
</td>
<td id="tblLastName">
#item.LastName
</td>
<td id="tblEmailID">
#item.EmailID
</td>
<td id="tblCustomerType">
#item.CustomerType
</td>
<td id="tblCustomerDesignation">
#item.CustomerDesignation
</td>
<td>
<div class="checkbox control-group">
<label><input type="checkbox" id="#item.CustomerID" value="#item.CustomerID"
onclick="AddRemoveCustomer(#item.CustomerID)" class="checkBoxClass"/>
#*#Html.CheckBox("Select", new { id = "cbCustomer", item.CustomerID})*#</label>
</div>
</td>
</tr>
}
</table>
<input type="hidden" id="hfCustomerID" />
In looking at your code, I noticed an issue that may be causing you the problem you indicate:
var index = CustomerIDArray.indexOf(currentCheckboxValue);
you then use index to decide if the Id is in the array, by doing this:
if (index == 0) {
it should be
if (index == -1) {
as -1 indicated not found. With it as it is currently, it would hit this line:
var a = CustomerIDArray.splice(index, 1);
and try to splice a negative index, which goes backward from the end of the string, which would give unexpected results.
Your hidden hfCustomerID field is always rendered to the browser as an empty field, because you haven't bound it to anything in your Model.
I assume this table is inside a form which is being posted to your controller? If so, then you could add a new field to your Model, and then use #Html.HiddenFor to render a hidden input field which is bound to that item in your model.
Alternatively, it looks like this field is entirely calculated based on the ticked checkboxes? In which case, update your view to set the value of the hidden field (this will duplicate some logic from your JavaScript though).
what i have is a grid, that is formed with combination of two tables. One section contain Header contents and other values added by user. Below is problem statment.
I have a div inside which a table resides. That make Header of the grid.
Another div having table in it. That contain rows for values.
Demonstration:
<div class="k-grid-header-wrap">
<table role="grid" id="Header" cellspacing="0">
<thead>
<tr>
<th class="k-header" role="columnheader" data-field="ColumnID_20_17_47" data-title="Q1">Q1</th>
<th class="k-header" role="columnheader" data-field="ColumnID_20_17_48" data-title="Q2">Q2</th>
<th class="k-header" role="columnheader" data-field="ColumnID_20_17_10048" data-title="Q3">Q3</th>
<th class="k-header" role="columnheader" data-field="ColumnID_20_17_10049" data-title="Q4">Q4</th>
<th class="k-header" role="columnheader" data-field="ColumnID_20_17_10050" data-title="Q5">Q5</th>
<th class="k-header" role="columnheader" data-field="ColumnID_20_17_10051" data-title="Q7">Q7</th>
<th class="k-header" role="columnheader" data-field="ColumnID_20_17_10052" data-title="Q8">Q8</th>
<th class="k-header" role="columnheader" data-field="ColumnID_20_17_10053" data-title="Q9">Q9</th>
<th class="k-header"></th>
</tr>
</thead>
</table>
</div>
<div style="height: 260px;" class="k-grid-content">
<table role="grid" id="tbl_1" cellspacing="0">
<tbody>
<tr class="" data-uid="a692c39b" role="row">
<td data-role="editable" class="" role="gridcell">1 </td>
<td data-role="editable" class="" role="gridcell">2</td>
<td data-role="editable" class="" role="gridcell">3</td>
<td data-role="editable" class="" role="gridcell">4</td>
<td data-role="editable" class="" role="gridcell">5</td>
<td data-role="editable" class="" role="gridcell">6</td>
<td data-role="editable" class="" role="gridcell">7</td>
<td data-role="editable" class="" role="gridcell">eight</td>
</tr>
</tbody>
</table>
</div>
Now what i want to do is against every row user enter in grid i want to push every grid cell values with ID to another table.
So forth what i have is:
function OnSave() {
var answerArray = [];
$("th[data-field*='_']").each(function () {
var Columnid = $(this).attr('data-field');
var Columntemp = Columnid.split('_');
var ColumnSection = Columntemp[1];
var ColumnQGroup = Columntemp[2];
var ColumnQuestion = Columntemp[3];
var ColumnRadiostatus = $(this).is(':checked');
var rowNum = $(this).parent().parent().index();
var ColumnValue;
$("#div1 table tbody tr").map(function (index, elem) {
// $('td', this).each(function () {
var tmp = $(this).find('td');
ColumnValue = $(tmp).val() || $(tmp).text();
if (!(ColumnValue instanceof Array))
{
ColumnValue = [ColumnValue];
}
answerArray.push(new clientAnswer(ColumnSection, ColumnQGroup, ColumnQuestion, ColumnRadiostatus, ColumnValue, rowNum));
//});
});
});
var serializedAnswers = Sys.Serialization.JavaScriptSerializer.serialize(answerArray);
PageMethods.UpdateAnswers(serializedAnswers, callBackUpdateAnswers);
}
function callBackUpdateAnswers(result) {
alert(result);
if (result == 'false') {
return false;
}
}
Which return whole row against every question.
Expected Output answerArray(20, 17, Q1, 1);
What's Now: answerArray(20, 17, Q1, 123456789);
Any Help would be appreciated. Regards
Following is solution for your issue:
function OnSave() {
var answerArray = [];
$("#Header th[data-field*='_']").each(function () {
var Columnid = $(this).attr('data-field');
var Columntemp = Columnid.split('_');
var ColumnSection = Columntemp[1];
var ColumnQGroup = Columntemp[2];
var ColumnQuestion = Columntemp[3];
var ColumnRadiostatus = $(this).is(':checked');
var rowNum = $(this).parent().parent().index();
var ColumnValue;
ColumnValue = $('#tbl_1 tr:eq(' + $(this).parent().index() + ') td:eq(' + $(this).index() + ')').text();
//alert("columnValue : " + ColumnValue);
if (!(ColumnValue instanceof Array)) {
ColumnValue = [ColumnValue];
}
answerArray.push(new clientAnswer(ColumnSection, ColumnQGroup, ColumnQuestion, ColumnRadiostatus, ColumnValue, rowNum));
});
var serializedAnswers = Sys.Serialization.JavaScriptSerializer.serialize(answerArray);
PageMethods.UpdateAnswers(serializedAnswers, callBackUpdateAnswers);
}
See Demo Here:
View Demo