How to get selected row values from a table - javascript

I am converting a HTML table to an array and passing it in to a controller for inserting multiple rows. I am able to create the array, but the problem is it's creating a complete table array but I want to get the selected row td values only.
//function to convert HTML table to array//
var HTMLtbl = {
getData: function (table) {
var data = [];
table.find('tr').not(':first').each(function(rowIndex, r) {
var cols = [];
// I believe the main problem is here:
$(this).find('td').each(function(colIndex, c) {
cols.push($(this).text().trim());
});
data.push(cols);
});
return data;
}
}
$(document).on('click', '#btnsave', function() {
var data = HTMLtbl.getData($('#tblresult'));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../Home/Save_SearchCarsDocs",
data: JSON.stringify(parameters)
});
request.done(function(msg) {
alert("Row saved " + msg.d);
});

You can try following...
//function to convert HTML table to array//
var excludedTD_Index = [0,5,7]; // define what you want to exclude by index
var HTMLtbl = {
getData: function (table) {
var data = [];
table.find('tr').not(':first').each(function(rowIndex, r) {
var cols = [];
// I believe the main problem is here:
$(this).find('td').each(function(colIndex, c) {
if(excludedTD_Index.indexOf(colIndex) >=0) // exclude TD
continue;
cols.push($(this).text().trim());
});
data.push(cols);
});
return data;
}
}
$(document).on('click', '#btnsave', function() {
var data = HTMLtbl.getData($('#tblresult'));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../Home/Save_SearchCarsDocs",
data: JSON.stringify(parameters)
});
request.done(function(msg) {
alert("Row saved " + msg.d);
});
OR you can make it more managable if you can add following data to your TD tag
<td data-exclude="1">
...
after adding above data you can exclude those columns as following
var HTMLtbl = {
getData: function (table) {
var data = [];
table.find('tr').not(':first').each(function(rowIndex, r) {
var cols = [];
// I believe the main problem is here:
$(this).find('td').each(function(colIndex, c) {
if($(this).data("exclude") == 1) // exclude TD
continue;
cols.push($(this).text().trim());
});
data.push(cols);
});
return data;
}
}

thanks Rory McCrossan finally get my answer i am adding my solution below
var CB=1;
var HTMLtbl =
{
getData: function (table) {
var data = [];
table.find('tr').not(':first').each(function (rowIndex, r) {
if ($("#chk_" + CB).is(':checked'))
{
var cols = [];
$(this).find('td').each(function (colIndex, c) {
cols.push($(this).text().trim());
});
data.push(cols);
}
CB++;
});
CB = 1;
return data;
}
}

Related

System.Data.Entity.DynamicProxies

I tried this code in my controller Can any one show me the solution:
public JsonResult GetMembers(Member member)
{
//var list = repository.GetAll().Select(x => new ViewModel.MemberView
//{
// Memberid = x.id,
// Name = x.name,
// EmailAddress = x.Email,
// Role = x.role.rolename,
// ReportingRoleId = Convert.ToInt32(x.reportingroleid)
//});
var list = repository.GetAll();
return Json(list , JsonRequestBehavior.AllowGet);
}
javascript function
<script type="text/javascript">
debugger;
alert('first');
google.load("visualization", "1", {packages:["orgchart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "/Organization/GetMembers",
data :'{member:"+JSON.stringify(member)+"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Member Name"+data);
//var data = new google.visualization.DataTable();
//data.addColumn('string','name');
//data.addColumn('string', 'role');
//data.addColumn('string', 'ToolTip');
//for (var i = 0; i < r.length; i++) {
// var memberId = r[i][0];
// var Name = r[i][1];
// var role= r[i][2];
// var reportingrole= r[i][3] != null ? r[i][3].toString() : '';
// data.addRows([[{
// v: employeeId,
// f: Name + '<div>(<span>' + role + '</span>)</div><img src = "/Pictures/' + memberId + '.jpg" />'
// }, reportingrole, role]]);
//}
// var chart = new google.visualization.OrgChart($("#chart")[0]);
// chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r);
},
error: function (r) {
alert(r);
}
});
}
It was Error
A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.NewProjects_A3B55EADDAEF6C59245BBD2495E29ECFE10B583596DB24AADF23A4990342D104'.
I had the same error, but this is worked for me, this is when you want to select
public MyDbContext() : base("name=MyDbContext"){this.Configuration.ProxyCreationEnabled = false;}
before you call yout table use this this.Configuration.ProxyCreationEnabled = false;
You should convert your data to list before returning it. EF return proxies for lazy loading and stuff. Try below code.
var list = repository.GetAll().ToList();
Also Look at this.
Why is EF returning a proxy class instead of the actual entity?

jQuery bind not working on click

I have a strange problem, from the ones below only the first one works, i need to mention that both of them are in jQuery(document).ready(function(){});
There are no errors in the console.
This one works
jQuery('.delete_product_line').click(function(){
console.log('xxxxx2');
});
This one doesn't work
jQuery('body').on('click', '.delete_product_line', function(){ console.log('ccccc');});
This is the full example, i know it does not make any sense, also the #submitAddProduct works as it should.
jQuery(document).ready(function(){
jQuery('body').on('click', '#submitAddProduct', function(){
var interval;
var product_id = jQuery('#add_product_product_id').val();
var price_tax_excl = jQuery('#add_product_product_price_tax_excl').val();
var price_tax_incl = jQuery('#add_product_product_price_tax_incl').val();
var qty = jQuery('#add_product_product_quantity').val();
var id_combination = 0;
var initial_rows = jQuery('#orderProducts tbody tr').length;
var i = 0;
var rows = 0;
console.log(initial_rows);
if(jQuery('#add_product_product_attribute_id').length > 0)
id_combination = jQuery('#add_product_product_attribute_id').val();
interval = setInterval(function(){
if(i >= 5000)
{
clearInterval(interval);
interval = 0;
}
else
{
rows = jQuery('#orderProducts tbody tr').length;
if(rows > initial_rows)
{
i = 10000;
var response_z = $.ajax({ type: "POST",
url: aem_ajax,
cache: false,
data: { action: 'add_product_to_order', id_product: product_id, price_tax_excl: price_tax_excl, price_tax_incl:price_tax_incl, qty:qty, id_combination: id_combination, id_order: aem_id_order, id_employee: aem_id_employee, token: aem_token },
async: true,
success: function(data) {
}
}).responseText;
}
}
i = i + 100;
}, 100);
return false;
});
jQuery('.delete_product_line').click(function(){
console.log('xxxxx2');
});
jQuery(document).on('click', '.delete_product_line', function(){
console.log('xxxxx');
var parent = jQuery(this).closest('tr');
var id_order_detail = parent.find('.edit_product_id_order_detail').val();
var price_tax_excl = parent.find('.edit_product_price_tax_excl').val();
var price_tax_incl = parent.find('.edit_product_price_tax_incl').val();
var qty = parent.find('.edit_product_quantity').val();
var id_combination = 0;
var link = 'https://mytestsite.com/'+parent.find('a:eq(0)').attr('href');
var url = new URL(link);
var id_product = url.searchParams.get("id_product");
var response_z = $.ajax({ type: "POST",
url: aem_ajax,
cache: false,
data: { action: 'remove_product_from_order', id_order_detail: id_order_detail, id_order: aem_id_order, id_product: id_product, id_employee: aem_id_employee,qty: qty, price_tax_excl:price_tax_excl, price_tax_incl:price_tax_incl, token: aem_token },
async: true,
success: function(data) {
}
}).responseText;
return false;
});
});
Use document instead of 'body' in this case.
jQuery(document).ready(function() {
jQuery(document).on('click', '.delete_product_line', function(){
console.log('ccccc');
});
})

View is not passing the model to controller - ASP.Net MVC

This is a basic passing of values from view to controller, but this does not seek to work.When I click the update button that functions to update the record in the database, the values from view, does not correctly pass the values to controller. Upon putting debugger in the javascript, the each variables were able to correctly got its values and evn the object where they are stored.
What could possible the reason for this problem?
here's the button onclick event code in Javascript.
$('#updatePrescription').click(function () {
debugger;
ValidateFields();
var drugListIsEmpty = CheckDrugList();
var error = $(".text-danger").length;
if (error == 0 && !drugListIsEmpty) {
debugger;
var prescription = [];
var template = {};
template.templateName = $("#prescriptionTemplateName").val();
template.templateTypeId = $('input[name=templateTypeId]:checked').val();
template.prescriptionTemplateItemList = [];
template.instructionId = $('.instruction').val();
template.frequencyId = $('.frequency').val();
template.day = $('.inputDays').val();
template.quantity = $('.inputQuantity').val();
template.dispenseLocationId = $('.selectDispenseLocation').val();
template.statusId = $('.status').val();
//template.categoryId = $('.templateCategory').filter(":visible").last().val();
template.templateId = $('#prescriptionTemplateId').val();
//if (template.categoryId == null) {
// template.categoryId = 0;
//}
var x = 0;
$('#tblPrescriptionSaveTemplateBody tr').each(function (key, value) {
debugger;
var row = $(this).closest('tr');
var next_row = $(row).next();
var drugId = $(value).find('.drugId').val();
var dosage = $(value).find('.inputDosage').val();
var dosageUnitId = $(value).find('.selectUnitId').val();
var statusId = "41";
var remarks = $(value).find('.inputDescription').val();
var groupId = $(value).find('.inputGroupNo').val();
var unit = $(value).find('.selectUnitId').val();
var prescriptionTemplateItemId = $(value).find('.prescriptionTemplateItemId').val();
x++;
var obj = {
// templateId: prescriptionTemplateId,
prescriptionTemplateId: template.templateId,
prescriptionTemplateItemId: prescriptionTemplateItemId,
drugId: drugId,
dosage: dosage,
dosageUnitId: dosageUnitId,
instructionId: template.instructionId,
frequencyId: template.frequencyId,
day: template.day,
quanitity: template.quantity,
unit: unit,
remarks: remarks,
dispenseLocationId: template.dispenseLocationId,
groupId: groupId,
statusId: template.statusId
}
template.prescriptionTemplateItemList.push(obj);
//prescription.push(obj)
})
$.ajax({
type: 'POST',
url: '/WestMedicinePrescriptionTemplate/UpdateTemplate',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(template),
success: function (data) {
ShowNotificationMessage(data.notification);
window.location.href = '/WestMedicinePrescriptionTemplate/Index';
}
});
}
});
This is expected to pass the result of model in parameter "newtemplate" in the controller, but it results to null
public ActionResult UpdateTemplate([FromBody] PrescriptionTemplateVM newtemplate)
{
int empId = Convert.ToInt32(HttpContext.Session.GetInt32("EmployeeId"));
var notif = "Update Failed.";
try
{
if (ModelState.IsValid)
{
bool updateSuccessful = _prescription.UpdatePrescriptionTemplateAndItems(newtemplate, empId);
if (updateSuccessful)
{
notif = "Update Successful.";
}
}
}
catch (Exception ex)
{
notif = ex.Message;
}
return Json(new { notification = notif });
}
What could be the problem in the code
do like this:
[HttpPost]
public ActionResult UpdateTemplate(PrescriptionTemplateVM newtemplate)
You need to make sure that you are using the same variables names that you defined in PrescriptionTemplateVM
and dont convert the data to Json. do like this:
$.ajax({
type: 'POST',
url: '/WestMedicinePrescriptionTemplate/UpdateTemplate',
dataType: 'json',
contentType: 'application/json',
data: {newtemplate: template},
success: function (data) {
ShowNotificationMessage(data.notification);
window.location.href =
'/WestMedicinePrescriptionTemplate/Index';
}
});

Iterate over array items and check property value

function GetViewModelData() {
var RDcViewModel = [];
var recordId = $.trim($("#recordId").val());
for (i = 1; i <= rowCount; i++) {
var item1 = $.trim($("#item1" + i).val()) == '' ? 0 : parseInt($("#item1" + i).val());
var item2 = $.trim($("#item2" + i).val()) == '' ? 0 : parseInt($("#item2" + i).val());
var GrandTotal = (item1 + item2);
var rdtCViewModel = new ItemDetailsViewModel(0, item1, item2, GrandTotal);
RDcViewModel.push(rdtCViewModel);
}
var obj = new ReportViewModel(recordId, RDcViewModel);
var viewmodel = JSON.stringify(obj);
return viewmodel;
}
I have the above sample function that i'm using to iterate over html table rows and storing the row values in an array.
Once i have my array populated, i'm using below code snippet to post the data to my controller.
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
//i want to check from here if viewmodel has any item(row) where GrandTotal is 0 (zero)
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function (data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function (e) {
return false;
}
});
});
}
What i now want to do in my PostData function is to check if my "viewmodel" object contains any item(row) where "GrandTotal" is 0.
using JSON.parse(viewmodel), prepare object of type ReportViewModel with RDcViewModel JS array of type ItemDetailsViewModel and iterate over it to find if any grandtotal == 0 for ItemDetailsViewModel instances
var viewmodel = GetViewModelData(),
var obj = JSON.parse(viewmodel);
var bFoundZero=false;
$.each(obj.RDcViewModelArray, function(idx, elem){
if( elem.GrandTotal === 0 ) bFoundZero=true;
})
if( bFoundZero ) return 0;
As you have stringified it, now you have to parse it back if you want to access its keys and values:
var PostData = function() {
$(".btnSubmit").click(function() {
var viewmodel = GetViewModelData(),
viewObj = JSON.parse(viewmodel),
flag = false; // <-----parse it back here
viewObj.forEach(function(i, el){
flag = el.GrandTotal === 0;
return flag;
});
if(flag){ return false; } // <------ and stop it here.
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function(data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function(e) {
return false;
}
});
});
}
There is no point iterating array again. Break the loop in GetViewModelData() and return false from that function. Then test it in PostData
Inside existing for loop:
var GrandTotal = (item1 + item2);
if(!GrandTotal){
return false;
}
Then in PostData()
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
if(viewmodel === false){
alert('Missing total');
return; //don't proceed
}
/* your ajax */

Loading data from controller to chart Jquery/ MVC/ C#

I have the following controller code to return chart data to jquery.
UPDATE: I have modified the code as suggested, but still getting error.
public JsonResult GetLeaveDataForPieChart(int user_id)
{
List<EmployeeLeaveHeader> elh1 = new List<EmployeeLeaveHeader>();
List<ChartEvent> ch = new List<ChartEvent>();
elh1 = itlbg1.EmployeeLeaveHeaders.Where(f => f.Employee_ID == user_id).ToList();
foreach (var item in elh1)
{
ChartEvent ce = new ChartEvent();
ce.value = (item.leaveAvailable * 100).ToString();
ce.color = item.CompanyLeaves.LeaveTypes.color;
ce.highlight = "#ffffff";
ce.label = item.CompanyLeaves.LeaveTypes.typeDescription + " Leave Available";
ch.Add(ce);
ChartEvent ce1 = new ChartEvent();
ce1.value = (item.leaveTaken * 100).ToString();
ce1.color = item.CompanyLeaves.LeaveTypes.color_light;
ce1.highlight = "#ffffff";
ce1.label = item.CompanyLeaves.LeaveTypes.typeDescription + " Leave Taken";
ch.Add(ce1);
}
return Json(ch, JsonRequestBehavior.AllowGet);
}
I need to retrieve data in jquery so that it is in the required format to be passed to pie data.
(document).ready(function () {
user_id = $("#user_id_1").text();
$.ajax({
url: '/Leave/GetLeaveDataForPieChart/',
cache: false,
data: { user_id: user_id },
type: "GET",
datatype: "json",
success: function (data) {
alert(data);
var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
var pieChart = new Chart(pieChartCanvas);
var PieData = $.each(data, function (idx, obj) {
var leave = new Object();
leave.value = obj.value;
leave.color = obj.color;
leave.highlight = obj.highlight;
leave.label = obj.label;
alert(leave);
return leave;
});
var pieOptions = {
//pie options..
};
pieChart.Doughnut(PieData, pieOptions);
}
});
Can anyone explain how to convert the json data to javascript object to be passed to the pie chart?
Here is how you parse JSON string into object.
var jsonObject = JSON.parse(jsonString);
here is how you use jquery to fetch the data and use it for your chart
$.ajax({
url: '/<Controller>/GetLeaveDataForPieChart/',
cache: false,
data: { user_id: <UserID> },
type: "GET",
success: function (data, textStatus, xmlHttpRequest) {
data = JSON.parse(data);
//....
//....
//Chart
//....
//....
//....
}
});

Categories

Resources