get selected row id jquery datatable row selection - javascript

i cannot get selected row id. I'm using datatable row selection. I'm getting [],[""] in console log. I have looked for other questions on SO and tried but no help
My javascript code is
$(document).ready(function () {
var selectedids = [];
var otable = $('#Table1').DataTable({
"bSort": false,
"rowCallback": function (row, data) {
if ($.inArray(data.DT_RowId, selectedids) !== -1) {
$(row).addClass('selected');
}
}
});
$('#Table1 tbody').on('click', 'tr', function () {
var id = this.id;
var index = $.inArray(id, selectedids);
var ids = $.map(otable.rows('.selected').data(), function (item) {
return item[0]
});
console.log(ids)
if (index === -1) {
selectedids.push(id);
console.log(selectedids);
} else {
selectedids.splice(index, 1);
}
$(this).toggleClass('selected');
});
});
I'm filling up my datatable with json data from controller in mvc
$('#ID').change(function () {
$("#t1 tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("")',
dataType: 'json',
data: { id: $("#ID").val() },
success: function (data) {
var items = '';
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td>" + item.id + "</td>"
+ "<td>" + item.yyy + "</td>"
+ "<td>" + item.aaa + "</td>"
+ "<td>" + item.eee + "</td>"
+ "<td>" + item.yyygg + "</td>"
+ "</tr>";
$('#Table1 tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});

You could spare yourself a lot of pain, if you used dataTables select extension :
var table = $('#example').DataTable({
select: {
style: 'multi'
}
})
var selectedIds = [];
table.on('select.dt', function(e, dt, type, indexes) {
selectedIds.push(indexes[0]);
console.log(selectedIds);
})
table.on('deselect.dt', function(e, dt, type, indexes) {
selectedIds.splice(selectedIds.indexOf(indexes[0]), 1);
console.log(selectedIds);
})
demo -> http://jsfiddle.net/0w1p7a3s/

Related

Search in .net MVC with AJAX. What can I do for the following code?

I want to do a search with AJAX. I simply did with the get method through passing search string in controller but that not I want
Below my controller code, where I get the search value from URL and return DATA (which is a list)
if (search != null)
{
if (search.ToLower().ToString() == "paid")
{
DATA = DATA.Where(a => a.Purchased_Price > 0).ToList();
}
else if (search.ToLower().ToString() == "free")
{
DATA = DATA.Where(a => a.Purchased_Price == 0).ToList();
}
else
{
DATA = DATA.Where(a => a.Purchased_File_Name.ToLower().StartsWith(search.ToLower()) || a.Purchased_Category.ToLower().StartsWith(search.ToLower()) || a.User1.Email.ToLower().StartsWith(search.ToLower()) || a.Purchased_Price.ToString().StartsWith(search)).ToList();
}
ViewBag.SoldList = DATA.ToPagedList(page ?? 1, pageSize); *this is what I actually did*
return Json(DATA , JsonRequestBehavior.AllowGet); *this is trial I do not know this work or not*
}
Below is the script which I wrote in view. Where I am going wrong? I'm not aware of that. I want whatever list comes with the help of whatever search I entered. To be printed in the table. Table is just above this script; I don't think it's needed so I did not include that.
<script>
$(document).ready(function () {
$("#search_button").on("click", function () {
var search_value = $("#searchText").val();
alert(search_value);
var SetData = $("#tabledata"); *tabledata is id of tbody tag *
SetData.html("");
console.log("setddata");
console.log(SetData);
$.ajax({
type: "get",
url: "/Home/MySoldNotes?search=" + search_value, *home is controller, mysoldnotes is action*
contentType: "application/ json; charset = utf - 8",
dataType: "html",
success: function (result) {
console.log("result");
console.log(result);
$.each(result, function (index, value) {
var data = "<tr>" +
"<td>" + value.NoteDetail.File_Name + "</td>" +
"<td>" + value.Purchased_Category + "</td>" +
"<td>" + value.User1.Email + "</td>" +
"<td>" + value.NoteDetail.Sell_Price + "</td>" +
"<td>" + value.Req_Solved_Date + "</td>" +
"</tr>"
SetData.append(data);
});
},
error: function (err) {
alert("Error aa gai");
console.log(err.responseText);
}
});
});
});
</script>
You must pass object to controller from ajax call. Example
<script>
$(document).ready(function () {
$("#search_button").on("click", function () {
var objParam = new Object();
objParam.search_value = $("#searchText").val();
$.ajax({
type: "POST",
url: "/Home/MySoldNotes"
contentType: "application/json; charset = utf-8",
data: JSON.stringify(objParam)
success: function (result) {
console.log("result");
console.log(result);
$.each(result, function (index, value) {
var data = "<tr>" +
"<td>" + value.NoteDetail.File_Name + "</td>" +
"<td>" + value.Purchased_Category + "</td>" +
"<td>" + value.User1.Email + "</td>" +
"<td>" + value.NoteDetail.Sell_Price + "</td>" +
"<td>" + value.Req_Solved_Date + "</td>" +
"</tr>"
SetData.append(data);
});
},
error: function (err) {
alert("Error aa gai");
console.log(err.responseText);
}
});
});
});
</script>
Then in your controller
public JsonResult MySoldNotes(string search_value)
{
// Do whatever and return json as result
}
List<BuyerReq> DATA = dc.BuyerReqs.Where(a => a.seller_id == ab && a.Status == true).AsQueryable().ToList();
return Json(DATA, JsonRequestBehavior.AllowGet);
while returning from the controller I am getting an error(not success my AJAX call).
but when I am doing this for testing purpose :
var aa = "checking"; return Json(aa, JsonRequestBehavior.AllowGet);
this works. I am not getting the exact error.

Limit no of rows in live search json data using $.each

I am trying to limit no of rows I am getting in live search JSON data through URL I tried counting no of table rows and return false but it doesn't work, is there any way of doing it.
$(document).ready(function() {
$.ajaxSetup({
cache: true
});
$('#search').keyup(function() {
$('#result').html('');
$('#state').val('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
$.getJSON('https://vast-shore-74260.herokuapp.com/banks?
city = MUMBAI ', function(data) {
$.each(data, function(key, value) {
var count = 0;
if ((value.city.search(expression) != -1 ||
value.branch.search(expression) != -1) && count < 10) {
$('#result').append('<tr><th>' + value.bank_name + '</th>' +
'<th>' + value.address + '</th>' +
'<th>' + value.ifsc + '</th>' +
'<th>' + value.branch + '</th>' +
'<th>' + value.bank_id + '</th></tr>'
count++;
}
else {
return false;
}
});
});
});
Try this - at least move the count=0 outside the loop
$(document).ready(function() {
$.ajaxSetup({
cache: true
});
$('#search').keyup(function() {
$('#result').html('');
$('#state').val('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
$.getJSON('https://vast-shore-74260.herokuapp.com/banks?city=MUMBAI', function(data) {
var count = 0;
$.each(data, function(key, value) {
if (count >= 10) return false;
if (value.bank_name.search(expression) != -1) {
$('#result').append('<tr><th>' + value.bank_name + '</th>' + '<th>' + value.bank_id + '</th></tr>');
count++;
}
});
});
});
});

Active or Inactive on Button click in ASP.Net MVC?

I am getting return json data from server,every value is inserted in table except status.
<script>
$(document).ready(function () {
$("#DomainID").change(function () {
var id = $(this).val();
$("#example tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
var items = '';
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
/*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/
var RoleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
if (item.ParentModuleID == -1) {
item.ModuleName = " -- " + item.ModuleName
}
else {
item.ModuleName = item.ModuleName
}
if (item.Status == "Y") {
item.Status = + '<img src="~/img/Active.png" height="32" width="32"/>'
}
else (item.Status == "N")
{
item.Status = + '<img src="~/img/InActive.png" height="32" width="32"/>'
}
var t = i + 1;
var rows = "<tr>"
+ "<td>" + t + "</td>"
+ "<td>" + item.ModuleName + "</td>"
+ "<td>" + item.Url + "</td>"
+ "<td>" + RoleName[i].RoleName + "</td>"
+ "<td>" + '' + item.Status + "</td>"
+ "</tr>";
$('#example tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
});
</script>
}
if item.Status == "N" means InActive image will display and if item.Status == "Y" means Active image will display
But in my code Status Value i didn't get any idea.?
Controller:
public ActionResult ViewModules(int id)
{
Domain_Bind();
dynamic mymodel = new ExpandoObject();
userType type = new userType();
List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
List<ViewRoleModules> RoleList;
List<ViewRoleModules> role = new List<ViewRoleModules>();
foreach (ViewRoleModules emp in EmpList)
{
RoleList = type.GetSiteRoleModulesViews(emp.ModuleID);
foreach (ViewRoleModules vip in RoleList)
{
role.Add(new ViewRoleModules
{
RoleName = vip.RoleName,
ModuleID = vip.ModuleID
});
}
}
var data = new { EmpList = EmpList, role = role };
return Json(data, JsonRequestBehavior.AllowGet);
}
Your code is a bit of a mess to be honest with several syntax errors. Hope this helps:
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
var roleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
var moduleName = item.ModuleName;
if (item.ParentModuleID == -1) {
moduleName = " -- " + moduleName;
}
var status = '';
if (item.Status == "Y") {
status = '<img src="~/img/Active.png" height="32" width="32"/>';
} else {
status = '<img src="~/img/InActive.png" height="32" width="32"/>';
}
var row = "<tr>" +
"<td>" + (i + 1) + "</td>" +
"<td>" + moduleName + "</td>" +
"<td>" + item.Url + "</td>" +
"<td>" + roleName[i].RoleName + "</td>" +
"<td>" + status + "</td>" +
"</tr>";
$('#example tbody').append(row);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});

filter duplicate rows with cake php and java script

I'm trying to filter table which is append using java script with cake php frame work .
and the following code is for adding this tables when i have click on add new magazine ,, but the problem is that , It's add double rows which has been added before . So i need to filter the added rows to delete the duplicated row.
/// function to show magazines data table
$('#add_researches_button').click(function () {
$("input[name='bstock_researchs_id[]']:checked").each(function (i) {
val[i] = $(this).val();
});
$.ajax({
type: "POST",
url: '../BstockIn/getResearchesIds/' + val,
dataType: "json",
success: function (data) {
$('#researches').css('display', 'block');
var res = $.parseJSON(data);
var CountResearches = 0;
jQuery.each(res, function (index, value) {
CountResearches++;
$("#researches").append("<tr><td>"
+ value.research_serial +
"</td><td>"
+ value.research_release_date +
"</td><td>"
+ value.research_release_hejry_date +
"</td><td>"
+ value.research_pages +
"</td><td>"
+ value.research_copies +
"</td></tr>"
);
});
/// function to show magazines data table
$('#add_researches_button').click(function() {
$("input[name='bstock_researchs_id[]']:checked").each(function(i) {
val[i] = $(this).val();
});
$.ajax({
type: "POST",
url: '../BstockIn/getResearchesIds/' + val,
dataType: "json",
success: function(data) {
$('#researches').css('display', 'block');
var res = $.parseJSON(data);
var CountResearches = 0;
jQuery.each(res, function(index, value) {
CountResearches++;
if ($("#researches tr[data-id='" + value.research_serial + "']").length == 0)
$("#researches").append("<tr data-id='" + value.research_serial + "'><td>" +
value.research_serial +
"</td><td>" +
value.research_release_date +
"</td><td>" +
value.research_release_hejry_date +
"</td><td>" +
value.research_pages +
"</td><td>" +
value.research_copies +
"</td></tr>"
);
});

MVC: Get JSON data from a controller using AJAX failed

I'm trying to query data using AJAX from a controller, my controller is:
[HttpGet]
public ActionResult GetTestStatus(string userName)
{
var db = new SREvalEntities();
var allTests = db.Tests
.Where(x => string.Equals(x.Owner, userName))
.Select(x => new { CreateDate = x.CreateDate, EndDate = x.EndDate, Status = x.Status })
.OrderByDescending(x => x.CreateDate)
.ToList();
return Json(allTests, JsonRequestBehavior.AllowGet);
}
And my javascript code in an extern file is:
function Filter() {
var userAlias = document.getElementById("UserAliasInput");
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias },
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
}
});
$("#ShowDetail").html(txt);
}
When I tried to debug this function, the code will never excute to
$("#ShowDetail").html(txt);
And my page will never be changed. How can I get it work? Thanks.
As you are using $.ajax(), which is asynchronous. Thus the $("#ShowDetail").html(txt) is called before the value is returned from API.
You should set the html() after the each block
function Filter() {
var userAlias = document.getElementById("UserAliasInput");
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias.value }, //Use the value property here
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
$("#ShowDetail").html(txt); //Move code to set text here
}
});
}
Try the following function
function Filter() {
var userAlias = $("#UserAliasInput").val();//change this
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias },
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
$("#ShowDetail").html(txt);//place this in the success function
}
});
}

Categories

Resources