Autocomplete for textbox Control under HTML table - javascript

I have a Html table(instead of Grid control I used HTML table) having multiple rows with one drop down and one textbox control.I want auto complete function for that text box.I implemented the following code for auto complete but it is firing for only first row.The rows are added Dynamically (in jquery) its not workig for those rows.
<table class="table table-bordered table-hover datatable-highlight" id="tWDE_Items">
<thead>
<tr>
<th style="display:none">ItemId</th>
<th>Item Name</th>
<th>UOM</th>
</tr>
</thead>
<tbody>
#foreach (var Item in Model.Data_Wde_ItemGrid)
{
<tr class="datarow">
<td style="display:none">#Item.Item_Id</td>
<td>#Html.EditorFor(m => Item.Item_Name, new { htmlAttributes = new { #class = "form-control" } }) </td>
<td>#Html.DropDownListFor(m => Item.UOM_Id, new SelectList(Item.UOMDetails, "UomId", "UomName"), htmlAttributes: new { #class = "form-control", id = "UomId" })</td>
</tr>
}
</tbody>
</table>
And Jquery code which I tried is as follows.
$(function () {
$('#Item_Item_Name').autocomplete({
source: function (request, response) {
debugger;
var param = { ItemName: $('#Item_Item_Name').val() };
$.ajax({
url: "/WDE/GetAutoCompleteItemList",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
val: item.split('÷')[0],
label: item.split('÷')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
change: function (e, i) {
if (i.item) {
}
else {
$('#Item_Item_Name').val('');
$('#Item_Item_Id').val('');
}
},
select: function (e, i) {
debugger;
$('#Item_Item_Name').val(i.item.label);
$(this).closest("tr").find("td").eq(2).html(i.item.val);
},
minLength: 1
});
});

You're saying
having multiple rows with one drop down and one textbox control. I want auto complete function for that text box
and I'm also seeing
$('#Item_Item_Name').autocomplete(...
Are you giving the same id to every textbox? If so, that will not work. Ids have to be unique. Jquery will assume you have only 1 and fire/listen to events only for that 1 textbox.
Consider rewriting your JS using classes for the textbox instead.

Related

JQuery Datatable Reload From Server MVC

I have a Datatable of JQuery generated at first-page load. I am trying to refresh it according to the selected criteria from the selectlist.
My Datatable initialized first like the following code.
<table class="table table-striped table-hover" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Select All <input type="checkbox" class="checkbox" id="chkBoxAll"></th>
#foreach (System.Data.DataColumn col in Model.DataTypesTable.Columns)
{
<th> #col.Caption</th>
}
</tr>
</thead>
<tbody>
#foreach (System.Data.DataRow row in Model.DataTypesTable.Rows)
{
<tr>
<td> <input type="checkbox" class="checkbox" name="chkBox" value="#row.ItemArray[0]"></td>
#foreach (var cell in row.ItemArray)
{
<td>
#cell.ToString()
</td>
}
</tr>
}
</tbody>
</table>
<script>
$(document).ready(function() {
$('#dataTable').DataTable();
});
</script>
It initializes well at first. However, when I try to reload it on the selectlistchange event, it doesn't reload anything and displays an error like this.
DataTables warning: table id=dataTable - Requested unknown parameter 'Id' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
<script type="text/javascript">
$("#slctDeviceList").change(function () {
var selectedValue = $("#slctDeviceList option:selected").text();
$.ajax({
traditional: true,
dataType: 'html',
type: "GET",
url: '#Url.Action("GetDeviceDataTypes", "Home")',
data: { slctDeviceList: selectedValue },
success: function (result) {
console.log("Success");
console.log(result);
$("#dataTable").DataTable({
destroy: true,
data: result,
columns: [
{ data: "Id", name: "Id" },
{ data: "Data Name", name: "Data Name" },
{ data: "Description", name: "Description" },
{ data: "Device Type", name: "Device Type" }
], columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}]
});
},
error: function (result) {
console.log("error");
}
});
});
</script>
Controller:
public JsonResult GetDeviceDataTypes(string slctDeviceList)
{
ChartRepository repository = new ChartRepository();
System.Data.DataTable dt = repository.GetDataTypes(slctDeviceList);
var json = this.Json(new { data = dt }/*, _jsonSetting*/);
return json;
}
My data is like below from the developer tools:
Please help me out to resolve the issue... Thanks in advance.
After long tries and losing hairs.. I have found a solution clear and add the rows again instead of destroy command. Here is the solution below.
<script type="text/javascript">
$("#slctDeviceList").change(function () {
var selectedValue = $("#slctDeviceList option:selected").text();
$.ajax({
traditional: true,
dataType: 'json',
type: "GET",
url: '#Url.Action("GetDeviceDataTypes", "Home")',
data: { slctDeviceList: selectedValue },
success: function (result) {
console.log("Success");
var dataTable = $("#dataTable").DataTable();
dataTable.clear().draw();
$.each(result, function myfunc (index, value) {
// use data table row.add, then .draw for table refresh
dataTable.row.add([
'<input type="checkbox" class="checkbox" name="chkBox" value="' + value.Id + '">',
value.Id,
value.DataName,
value.Description,
value.DeviceType
]).draw();
});
},
error: function (result) {
console.log("error");
}
});
});
</script>
Also, it is important to return a json object from the controller action.
PS. If the Json Object has an initial tag like data, you may need to change the looping value.Id to value.data.Id. But it is better to not use any tag.
public JsonResult GetDeviceDataTypes(string slctDeviceList)
{
ChartRepository repository = new ChartRepository();
System.Data.DataTable dt = repository.GetDataTypes(slctDeviceList);
JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };
var json = this.Json(dt , _jsonSetting);
return json;
}

under HTML table Autocomplete for HtmlEditor Control

I have a Html table having multiple rows with one drop down and one textbox control.
I want auto complete function for that text box.I implemented the following code for auto complete but it is firing for only first row.The rows are added Dynamically (in jquery) its not workig for those rows.
CODE:
<table class="table table-bordered table-hover datatable-highlight" id="tWDE_Items">
<thead>
<tr>
<th style="display:none">ItemId</th>
<th>Item Name</th>
<th>UOM</th>
</tr>
</thead>
<tbody>
#foreach (var Item in Model.Data_Wde_ItemGrid)
{
<tr class="datarow">
<td style="display:none">#Item.Item_Id</td>
<td>#Html.EditorFor(m => Item.Item_Name, new { htmlAttributes = new { #class = "form-control" } }) </td>
<td>#Html.DropDownListFor(m => Item.UOM_Id, new SelectList(Item.UOMDetails, "UomId", "UomName"), htmlAttributes: new { #class = "form-control", id = "UomId" })</td>
</tr>
}
</tbody>
</table>
Java Script :
$('#Item_Item_Name').autocomplete({
source: function (request, response) {
debugger;
var param = { ItemName: $('#Item_Item_Name').val() };
$.ajax({
url: "/WDE/GetAutoCompleteItemList",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
val: item.split('÷')[0],
label: item.split('÷')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
change: function (e, i) {
if (i.item) {
}
else {
$('#Item_Item_Name').val('');
$('#Item_Item_Id').val('');
}
},
select: function (e, i) {
debugger;
$('#Item_Item_Name').val(i.item.label);
$(this).closest("tr").find("td").eq(2).html(i.item.val);
},
minLength: 1
});
Your autocomplete() call works only on the elements that are in the dom the time you call it. So for dynamically added elements you'll need the call the function again (after the new row was added).
One more thing to notice is that any call using the element id ($('#Item_Item_Name')) will work only for the first element with that id, because ids are meant to be unique. So you'll need to change the selector to get the input from the new row.
Create a function that inits the autocomplete And after every row you add, call that function on the element you want.
function initAutoComplete(elem) {
$(elem).autocomplete({ /* the same as you use now */ });
}
// after you addded the new row
initAutoComplete($(newRow).find('.autocopmlete-input'));

How to update the Model value and reload a div in Razor view in MVC

This is my code in Razor view that basically displays the table by extracting information from database -
#model List<EmpoyeeInfo.Models.FFX_HR_Employees>
#using System.Reflection;
#{
ViewBag.Title = "Employee Information";
var Properties = Model[0].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
string[] head = new string[Properties.Count()];
}
<div id="web-top">
<div id="horizontal-line"></div>
<input class="search-box-text" type="text" spellcheck="false" placeholder="Search Individual Record..." title="Search Individual Record" id="searchbox" name="searchbox" />
</div>
<div id="web-main">
<table class="employee-info">
<tr>
#foreach (var Property in Properties)
{
if (Property.Name.Equals("AnnualHolidayEntitlement"))
{
<th colspan="2">#Property.Name</th>
}
else
{
<th>#Property.Name</th>
}
}
</tr>
#foreach(var Row in Model)
{
<tr>
#{
Type type = Row.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(type.GetProperties());
}
#foreach (PropertyInfo prop in props)
{
if (prop.Name.Equals("AnnualHolidayEntitlement"))
{
<td contenteditable="true">#prop.GetValue(Row, null)</td>
}
else
{
<td>#prop.GetValue(Row, null)</td>
}
}
<td class="saveToDB">SAVE</td>
</tr>
}
</table>
</div>
but as i type in the search box text, an ajax calls are made -
$(document).ready(function () {
$('.search-box-text').keypress(function () {
getReport($(this).html());
});
})
function getReport(Name) {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
data: { Name: Name },
dataType: "json",
cache: false,
success: function (result) {
//do stuff;
},
error: function () {
console.log("no display");
}
});
}
now how do i reload the div - "web-main" and update the Model value such that as the user searches for a name, the table also needs to be updated.
Code below will append the results to the div 'web-main'. You need to manipulate the success portion of jQuery in your code
$(document).ready(function () {
$('.search-box-text').keypress(function () {
getReport($(this).html());
});
})
function getReport(Name) {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
data: { Name: Name },
dataType: "json",
cache: false,
success: function (data) {
//do stuff;
console.log(data);
$("web-main").append(JSON.stringify(data));
},
error: function () {
console.log("no display");
}
});
}

I do not know why this Java Script code not run in MVC

In dropdownlist onchange event call FillSystem() Ajax Request is sent but scopeId selector do not run this below method.
function FillSystem() {
var _scopeId = $('#ScopeId').val();
var _roleId = $('#Role_Id').val();
$.ajax({
url: '/Account/FillSystem',
type: "GET",
dataType: "JSON",
data: { scopeId: _scopeId, roleId: _roleId },
success: function (systems) {
$("#SystemId").html(""); // clear before appending new list
$.each(systems, function (i, system) {
$("#SystemId").append(
$('<option></option>').val(system.System_Id).html(system.SystemName));
});
}
});
}
<table class="table w3-striped w3-border w3-card-4" style="width: 65%">
<tr>
<td>
Scope
</td>
<td>
#Html.DropDownList("ScopeId", null,"--Please Select--", new { style = "width:250px", #onchange = "FillSystem()" })
</td>
</tr>
<tr>
<td>System</td>
<td>
#Html.DropDownList("SystemId", null, "--please select--", new { style = "width:250px" })
</td>
</tr>
</table>
you use DropDown in table and probably multiple row exist, and multiple id with same, your $('#ScopeId') selector, select first element with ScopeId.
first remove #onchange = "FillSystem()" from DropDownList, then try this code
(function ($) {
function FillSystem() {
var _scopeId = $(this).val();
var _roleId = $('#Role_Id').val();
var $row = $(this).closest("tr");
$.ajax({
url: '/Account/FillSystem',
type: "GET",
dataType: "JSON",
data: { scopeId: _scopeId, roleId: _roleId },
success: function (systems) {
$("#SystemId", $row).html(""); // clear before appending new list
$.each(systems, function (i, system) {
$("#SystemId", $row).append(
$('<option></option>').val(system.System_Id).html(system.SystemName));
});
}
});
}
$(function () {
$("table").on("change", "#ScopeId", FillSystem)
});
}(jQuery));

Dynamically adding table rows with functions

I have a table that I need to dynamically add/remove rows from. Each row has a hyperlink in the final column to remove the record. Since you can dynamically add rows after the page loads, occasionally this record won't be found in the database.
When the user clicks on the "Delete" link, an ajax function is called to remove the record from the database. As long as the function server-side function does not crash, the operation will send back as a success.
Once the ajax function's success function is called, I would like to remove the tr from the table.
I can do this with each row that exists in the table once the page loads. The ajax function sends the proper info back to the server, and the tr is removed from the table. However for each tr I add after the delete ajax function will not fire, and the tr is left on the page.
View
<fieldset>
<legend>Agent Ids</legend>
<table id="agentTable">
<thead>
<tr>
<th>State Code</th>
<th>Company Code</th>
<th>Agent ID</th>
<th>Non-Res Biz NY</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.BankListAgentIds)
{
#Html.Partial("AgentIdPartial", item)
}
</tbody>
Add Another
</table>
</fieldset>
Parial View
#model CollectionItemTest.Models.BankListAgentId
#{
Layout = null;
}
#using (Html.BeginCollectionItem("BankListAgentIds"))
{
#Html.HiddenFor(model => model.TableId)
#Html.HiddenFor(model => model.BankID)
<tr>
<td>
#Html.EditorFor(model => model.StateCode)
</td>
<td>
#Html.EditorFor(model => model.CompanyCode)
</td>
<td>
#Html.EditorFor(model => model.NonResBizNY)
</td>
<td>
#Html.EditorFor(model => model.AgentId)
</td>
<td>
#Html.ActionLink("Delete", "", "", new { href = "javascript:void(0)", id = Model.TableId })
</td>
</tr>
}
jQuery
<script type="text/javascript">
$(function() {
$('#agentTable').on('click', 'tr a', function(e) {
$.ajax({
url: '#Url.Action("DeleteRow", "BankList")',
data: { id: $(this).attr('id') },
dataType: 'html',
cache: false,
context: this,
success: function () {
$(this).parents('tr').remove();
}
});
})
});
$(document).ready(function () {
$('.addCode').click(function() {
$.ajax({
url: '#Url.Action("BlankRow", "BankList")',
dataType: 'html',
cache: false,
success: function(html) {
$("#agentTable > tbody").append(html);
}
});
});
});
</script>
Controller Functions
public JsonResult DeleteRow(int id)
{
if (id == 0) return null;
var agent = (from a in db.BankListAgentIds
where a.TableId == id
select a).FirstOrDefault();
if (agent == null) return Json("Agent Id not found", JsonRequestBehavior.AllowGet);
db.BankListAgentIds.Remove(agent);
return null;
}
public ViewResult BlankRow()
{
return View("AgentIdPartial", new BankListAgentId());
}
Followed this post and used the .live command.
$('#agentTable').live('click', 'tr a', function (e) {
$.ajax({
url: '#Url.Action("DeleteRow", "BankList")',
data: { id: $(this).attr('id') },
dataType: 'html',
cache: false,
context: this,
success: function () {
$(this).parents('tr').remove();
}
});
});

Categories