Unable to add row in the middle of jQuery datatables(with FIDDLE) - javascript

I am trying to add new rows to the table using the rows.add() function in the DataTables API. The data is coming from the server using AJAX call.
Here is an example to work upon - FIDDLE
My Table Structure is follows:
<table id="myTable">
<thead>
<th>
Id
</th>
<th>
Name
</th>
<th>
Designation
</th>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.Number
</td>
<td>
#item.Name
<img id="imgA" onclick="AddNewRows();" class="iterationChild" src="#Url.Content("~/Images/plus.png")" alt="expand/collapse" />
</td>
<td>
#item.Designation
</td>
</tr>
}
</tbody>
</table>
Corresponding Javascript function:
function AddNewRows() {
$.ajax({
type: 'GET',
url: '#Url.Action("NewRows", "Home")',
dataType: "json",
async: true,
success: function (data) {
var table = $('#myTable').DataTable();
for (var i = 0, l = data.length; i < l; i++) {
//how to add it just after the current row clicked
table.row.add([
data[i].Number,
data[i].Name,
data[i].Designation
]).draw();
}
},
error: function (result) {
alert('error');
}
});
}
I want to be able to add the new row after the row which is clicked. Here it is adding at the end of the table(last rows).

Assuming every row as a unique id, try passing the current row clicked id into your function as a parameter. Example:
function AddNewRows(id) {
var my_row = document.getElementById(id);
...

Related

How do i refresh or redraw table rows

Below is the classical issue which I am facing during my app development.
I have an array of JSONObjects in my spring controller that I have to iterate in the jsp;
Also another status attribute called JSONArrayStatus is set that suggests if JSON array is empty or not.
Using jquery if JSONArray is empty I will show noDataImageDiv otherwise will show tableDIV (Binding the data from JSONArray using JSTL)
The problem I am facing is as below.
1. Edit a row in the table and click on Update. At this time I make an Ajax Call say, "UpdatedUser", which will return all the records along with the updated records. I could use refresh however thats not a recommended user experience and hence a no no.
To reflect the updated users in the table, I use jquery as below
clearing table rows table.clear().draw()
Loop the result set as follows.
redraw code
function reDrawExternalContactUsers(externalUsers) {
table.clear().draw();
var row = "";
$.each(externalUsers, function (i, field) {
row = '<tr><td></td><td></td><td class="edit">edit</td></tr>';
$("#tableDIV").append(row);
});
}
afetr this redraw or refresh process
This function is NOT working
$(".edit").click(function(){
});
This function is working
$("#tableDIV .edit").click(function(){
});
Suggest a better way of refreshing table rows, if any.
<div id="tableDIV">
<table id="tableID">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
if data exist
loop{
<tr>
<td></td>
<td></td>
<td class="edit">edit</td>
</tr>
} // loops ends
if close
</tbody>
</table>
</div>
<div id="noDataImageDiv"> No data image</div>
html code :
<div id="tableDIV">
<table id="tableID">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
if data exist
loop{
<tr>
<td class="user-name"></td>
<td></td>
<td class="edit" data-user-id="">edit</td> //set user_id in attr data-user-id
</tr>
} // loops ends
if close
</tbody>
</table>
</div>
<div id="noDataImageDiv"> No data image</div>
jquery code :
you should use click event on document
$(document).on('click', '.edit', function () {
var btn = $(this);
var user_id = btn.attr("data-user-id"); //user_id of user will update
// extra user data
$.ajax({
method: "POST",
url: url,
data: {
'id': id,
// extra data to send
},
success: function (data) {
if (data.status) // successfully user updated
{
var user = data.user;
/* you can set user data like this */
btn.closest('tr').find('.user-name').html(user.name);
}
}
});
});

Add Link Column to DataTable After Ajax Call MVC

On my view page I have a table (from a partial view) and a form. I am using ajax to submit the form to my webapi controller.
On success I would like to add what was entered in the textbox to the first column, and links to Edit and Delete in the second column of a new row.
As of right now I am only working on the Edit link.
Here is my partial view table:
<table id="Table" class="table table-bordered">
<thead>
<tr>
<th class="col-md-6">
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
</thead>
#foreach (var item in Model)
{
<tr>
<td class="col-md-6">
#Html.DisplayFor(modelItem => item.Admin)
</td>
<td class="col-md-6">
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>
Here is my form jquery.ajax:
var table = $("#Table").DataTable({
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [1] },
{ "bSearchable": false, "aTargets": [1] }
]
});
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
url: infoGetUrl,
method: "post",
data: $("form").serialize()
}).success(function (data) {
var editLink = document.createElement('a');
editLink.href = "/controllerName/Edit/" + data.id;
editLink.text = "Edit";
table.row.add([
$("#Textbox").val(),
editLink
]).draw();
}).error(function(jqXHR, textStatus, errorThrown) {
console.log("error");
});
});
The problem is that when this renders I get this:
It is not clickable and renders like this:
<tr class="even" role="row">
<td class="sorting_1">John.Doe</td>
<td>http://localhost:61888/controllerName/Edit/15</td>
</tr>
As you can see, it is not rendered in an a tag, and I don't need the http://localhost:61888 part of the link.
How can I resolve this?
try creating link as:
var link = <a href='/controllerName/Edit/' + data.id>EDIT</a>
With pur JS:
var link = document.createElement('a');
link.textContent = 'Edit';
link.href = "/controllerName/Edit/" + data.id;
you just need to place this inside your td.
If you want to remove 'http://localhost:61888' you can just use replace to change your localhost by un empty string. Or split your string and just keep the second part

How to get values of dynamically generated text box and make ajax request to controller in mvc4 and jquery?

I have one table where I am dynamically generating textbox's and binding model values to those textboxe's. Also i have one button. I want to send dynamically generated textbox values in Ajax request. My code is as below.
#foreach (var group in Model.Groups)
{
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="dataTable tableHover">
<tr>
#foreach (var item in group.Items)
{
<th>#item.Label</th>
}
</tr>
<tr>
#foreach (var item in group.Items)
{
<td><input type="text" id="Value" value="#item.Value"></td>
}
</tr>
</table>
}
#foreach (var group in Model.Groups)
{
<tr>
#{ int k = 1; }
#foreach (var item in group.Items)
{
if (k == 1)
{
<td scope="col"> <button type="button" class="btn btn-primary" id="SaveUpdate" onclick="updatemetaData('#item.upld_id,#item.Value');">Save</button></td>
k = 0;
}
}
</tr>
}
this is my jquery function to make ajax request.
function updatemetaData(docid) {
$.ajax(
{
type: "GET",
data: { upld_id: docid },
dataType: "html",
url: '/documentVerification/updatedocDetails',
headers: {
'VerificationToken': forgeryId
},
success: function (data)
{
$('#GridDetails').html("");
$('#GridDetails').html(data);
$("#dialog-formdocumentdata").dialog('open');
}
, error: function (error)
{
}
});
}
</script>
I want to send values of dynamically generated textboxes in ajax call. In the below code 2 text boxe's will generate in all cases.
#foreach (var item in group.Items)
{
<td><input type="text" id="Value" value="#item.Value"></td>
}
Is it possible in jquery to achieve this? Thank you in advance.
I can't spot a computer around. Be careful following code may contain errors.
Use nuget to import Newtonsoft Json assembly.
In the controller add:
using Newtonsoft.Json;
ViewBag.JsonData = JsonConvert.SerializeObject(yourObjectContainingRandomNumbers);
In the view:
#Html.Hidden("inputID", Viewbag.JsonData)
Move jquery reference to the hidden field and things should work.

Auto refreshing multiple divs MVC

I want to update a column of data in a table in MVC view.
This is the View that I want to update.
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CurrentTemperature)
</th>
<th></th>
</tr>
#{int i = 1;}
#foreach (var item in Model)
{
<tr>
<td align="center" #*id="#("current"+i)" data-id="#item.ID"*#>
<div id="#("current"+i)" data-id="#item.ID">
#{Html.RenderAction("TemperatureUpdateDeviceList", new { idDevice = item.ID });}
</div>
</td>
</tr>
i++;
}
</table>
I wrote a simple script in order to update the divs. Just for trying I decided to update only the 4th div with id= current4.
$(function () {
setInterval(function () {
var id = $(this).attr('data-id');
$.ajax({
url: '#Url.Action("TemperatureUpdateDeviceList")',
type: 'GET',
data: { idDevice: id},
}).success(function (partialView) {
$('#current4').html(partialView);
});
},3000);
});
Using this method I can't perform a correct request because the generated URL is not correct. How to have a correct URL?
Notice that TemperatureUpdateDeviceList function is defined as:
public PartialViewResult TemperatureUpdateDeviceList(int idDevice)
{
return PartialView(temperatureModel);
}
You use of var id = $(this).attr('data-id'); will not pass the data-id value because $(this) is not your <div> element. If you want to update all your elements, then change the html to
<div class="container" data-id="#item.ID">
#{Html.RenderAction("TemperatureUpdateDeviceList", new { idDevice = item.ID });}
</div>
Note the id attribute is not necessary. Then in the script use
var url = '#Url.Action("TemperatureUpdateDeviceList")';
setInterval(function () {
$('.container').each(function() {
var id = $(this).data('id');
var div = $(this);
$.get(url, { idDevice: id}, function(partialView) {
div.html(partialView);
});
});
},3000);

Hide "No data available in table" message when data is present

This is my table , I get the data list using json and populate this table,
<table id="tblClaimSearch" class="display responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th><input type="checkbox" id="ChkboxClaimHeader" name="ChkboxClaimHeader" value="false"></th>
<th>Claim #</th>
<th>Client Name</th>
<th>Amount</th>
<th>Deduction</th>
<th>Type</th>
<th>Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
My jquery which has Json result, I get the result and append rows to table body based on my data,
$(document).ready(function () {
$.ajax({
url: '#Url.Action("ClaimResultTest", "Claims")',
data: { seacrhClaimNumber: claimNumberToBeSearched },
type: 'POST',
success: function (data) {
var dataClaims = data.Claims;//This has the complete list
for (i = 0; i < dataClaims.length; i++) {
alert(dataClaims[i].ClaimNumber);
$("#tblClaimSearch").find('tbody')
.append($('<tr>')
.append($('<td><input type="checkbox">'))
.append($('<td>').text(dataClaims[i].ClaimNumber))
.append($('<td>').text(dataClaims[i].Client))
.append($('<td>').text(dataClaims[i].Amount))
.append($('<td>').text(dataClaims[i].Deduction))
.append($('<td>').text(dataClaims[i].Type))
.append($('<td>').text(dataClaims[i].Status))
)
}
}
});
});
The problem is when there is no data, I have a row displaying "No data available in table"..And even when there is data appended I still have first row as "No data available in table"..How do I hide this message row when new rows with data have been added??And secondly even though I have 16 entries it still shows "Showing 0 of 0 entries"?.What am I doing wrong?..
try this:-
$(document).ready(function () {
$.ajax({
url: '#Url.Action("ClaimResultTest", "Claims")',
data: { seacrhClaimNumber: claimNumberToBeSearched },
type: 'POST',
success: function (data) {
$("#tblClaimSearch").find('tbody').empty(); //add this line
var dataClaims = data.Claims;//This has the complete list
for (i = 0; i < dataClaims.length; i++) {
alert(dataClaims[i].ClaimNumber);
$("#tblClaimSearch").find('tbody')
.append($('<tr>')
.append($('<td><input type="checkbox">'))
.append($('<td>').text(dataClaims[i].ClaimNumber))
.append($('<td>').text(dataClaims[i].Client))
.append($('<td>').text(dataClaims[i].Amount))
.append($('<td>').text(dataClaims[i].Deduction))
.append($('<td>').text(dataClaims[i].Type))
.append($('<td>').text(dataClaims[i].Status))
)
}
}
});
});

Categories