jQuery autocomplete will not loop through XML data - javascript

Currently, I cannot seem to retrieve any of the data from my XML file. Below is the code;
$(document).ready(function() {
setTimeout(function() {
$('#_Q0').autocomplete({
source: function(request, response) {
$.ajax({
url: "brands.xml",
dataType: "xml",
type: "GET",
success: function(xml) {
var results = [];
$(xml).find("brand").each(function() {
if (results.indexOf(request.term.toUpperCase()) >= 0) {
results.push(results);
}
});
response(results);
}
});
},
autoFocus: true,
minLength: 3,
response: function(event, ui) {
if (!ui.content.length) {
var noResult = {
value: "",
label: "No results found"
};
ui.content.push(noResult);
}
}
});
var render = $('#_Q0').autocomplete('instance')._renderMenu;
$('#_Q0').autocomplete('instance')._renderMenu = function(ul, items) {
items.push({
label: 'AUTRE MARQUE',
value: 'AUTRE MARQUE',
last: true
});
render.call(this, ul, items);
};
}, 100);
});
and here is a Plunk;
https://plnkr.co/edit/QFOYcJc7iQ8UQc0e5SKH?p=preview
I was previously working with a JSON source, but now have to switch to XML.
Thanks in advance

Th problem is in processing the xml
$(document).ready(function() {
setTimeout(function() {
$('#_Q0').autocomplete({
source: function(request, response) {
$.ajax({
url: "brands.xml",
dataType: "xml",
type: "GET",
success: function(xml) {
var term = request.term.toLowerCase();
var results = $(xml).find("brand").filter(function() {
return $(this).attr('label').toLowerCase().indexOf(term) > -1;
}).map(function() {
return {
label: $(this).attr('label')
}
}).get();
response(results, xml);
}
});
},
autoFocus: true,
minLength: 3,
response: function(event, ui) {
if (!ui.content.length) {
var noResult = {
value: "",
label: "No results found"
};
ui.content.push(noResult);
}
}
});
var render = $('#_Q0').autocomplete('instance')._renderMenu;
$('#_Q0').autocomplete('instance')._renderMenu = function(ul, items) {
items.push({
label: 'AUTRE MARQUE',
value: 'AUTRE MARQUE',
last: true
});
render.call(this, ul, items);
};
}, 100);
});
Demo: Plunker

Related

using jquery ui autocomplete but styles hiding

I ma using jquery UI auto complete and i am getting the results, the only problem i am getting the results
http://prntscr.com/rsm946
not sure why it is not display, the json is coming as correct
my JSOn
[{"name":"author","type":"U","status":"0","owner":"dbo"},{"name":"author_dates","type":"U","status":"0","owner":"dbo"}]
$("#student").autocomplete(
{
source: function(request, response) {
$.ajax({
url: "search.cfc?method=searchByName&returnformat=json",
dataType: "json",
data: {
search: request.term,
maxRows: 10
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.label, value: item.label
};
}));
}
})
},
select: function( event, ui ) {
$('#submit').css("display", "block");
}
});
Please consider the following:
$("#student").autocomplete({
source: function(request, response) {
$.getJSON("search.cfc", {
method: "searchByName",
returnformat: "json",
search: request.term,
maxRows: 10
}, function(data) {
response($.map(data, (item) => {
return $.extend(item, {
label: item.name,
value: item.name,
});
}));
});
},
select: function(event, ui) {
$('#submit').css("display", "block");
}
});
Your object attribute is name, not label so u should write name despide of label
$("#student").autocomplete(
{
source: function(request, response) {
$.ajax({
url: "search.cfc?method=searchByName&returnformat=json",
dataType: "json",
data: {
search: request.term,
maxRows: 10
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.name, value: item.name
};
}));
}
})
},
select: function( event, ui ) {
$('#submit').css("display", "block");
}
});

Uncaught ReferenceError: function is not defined at HTMLButtonElement.onclick error on button inside datatable

I am having some problems using datatables.net with requirejs and some buttons and data loaded through the ajax request from datatables.net (JSON). I have tried and tried but still no luck.
The problem I face is: Uncaught ReferenceError: editPermission is not defined at HTMLButtonElement.onclick (permissions.php:1)
Here is the full backend PHP function that is connecting to the DB:
public function getAllPermissions($request, $columns): array
{
$bindings = array();
try {
$sql = "SELECT p.id, p.name, p.description, p.category, NULL AS roles,
CASE WHEN
p.required = 0 THEN concat('<button id=\'editpermission_', p.id, '\' onclick=\'editPermission(',p.id,')\' class=\'btn btn-warning\'>Edit</button>')
ELSE null END
AS edit
FROM ".$this->tbl_permissions." p";
$stmt = $this->conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$return_data = array(
"data" => MiscFunctions::data_output($columns, $data)
);
return $return_data;
} catch (\PDOException $e) {
http_response_code(500);
$result = ["Error" => $e->getMessage()];
return $result;
}
}
Under here is the file that ajax asks for the data (permissions_getall.php):
<?php
try {
require '../../vendor/autoload.php';
session_start();
$request = new PHPLogin\CSRFHandler;
$auth = new PHPLogin\AuthorizationHandler;
$admin = new PHPLogin\AdminFunctions;
if ($request->valid_token() && ($auth->isSuperAdmin() || $auth->hasPermission('View Permissions'))) {
unset($_GET['csrf_token']);
$columns = array(
array( 'db' => 'id', 'dt' => 0 ),
array( 'db' => 'name', 'dt' => 1 ),
array( 'db' => 'description', 'dt' => 2 ),
array( 'db' => 'category', 'dt' => 3 ),
array( 'db' => 'roles', 'dt' => 4 ),
array( 'db' => 'edit', 'dt' => 5 )
);
$data = $admin->getAllPermissions($_GET, $columns);
echo json_encode($data);
} else {
http_response_code(401);
throw new Exception('Unauthorized');
}
} catch (Exception $e) {
error_log($e->getMessage());
echo json_encode($e->getMessage());
}
This is the JS file:
require(['jquery', 'multiselect', 'datatables', 'datatables.net', 'datatables.net-bs4', 'datatables.net-buttons', 'datatables.net-buttons-bs4', 'datatables.net-select-bs4', 'loadingoverlay'], function ($) {
console.log($);
//User Management scripts
/* HANDLES POPOVERS FOR USER INFO */
function userInfoPull(id, elem) {
$.ajax({
type: "POST",
url: "ajax/user_getinfo.php",
data: {"user_id": id, "csrf_token": $('meta[name="csrf_token"]').attr("value")},
async: false,
beforeSend: function () {
$.LoadingOverlay('show', {
image: '../login/images/Spin-0.8s-200px.svg',
imageAnimation: false,
imageColor: '#428bca',
fade: [200, 100]
});
},
complete: function () {
$.LoadingOverlay("hide");
},
success: function (user_info) {
user_info = JSON.parse(user_info);
var user_info_html = '';
for (var prop in user_info) {
if (user_info[prop] != '' && user_info[prop] != null) {
if (prop == 'UserImage') {
user_info_html += '<br><div class="img-thumbnail"><img src="' + user_info[prop] + '" height="240px"></div>';
} else {
user_info_html += '<div><b>' + prop.replace(/([A-Z])/g, ' $1') + ': </b>' + user_info[prop] + '</div>';
}
}
}
$(elem).attr('data-content', user_info_html).popover('show', {"html": true});
},
error: function (xhr, error, thrown) {
console.log(error);
}
});
};
$('body').on('mouseover', "a[id^='info_']", function () {
if ($(this).attr('data-content')) {
$(this).popover('show', {"html": true});
} else {
var id = this.id.split('_')[1];
userInfoPull(id, this);
}
});
$('body').on('mouseleave', "a[id^='info_']", function () {
$(this).popover('hide');
});
/****************************/
/* HANDLES MODAL FOR PERMISSION ROLES */
$('body').on('click', "button[id^='rolesbtn_']", function () {
var id = this.id.split('_')[1];
permissionRolesList(id);
});
function permissionRolesList(id) {
$.ajax({
type: "POST",
url: "ajax/permission_getroles.php",
data: {"permission_id": id, "csrf_token": $('meta[name="csrf_token"]').attr("value")},
beforeSend: function () {
$.LoadingOverlay('show', {
image: '../login/images/Spin-0.8s-200px.svg',
imageAnimation: false,
imageColor: '#428bca',
fade: [200, 100]
});
},
complete: function () {
$.LoadingOverlay("hide");
},
success: function (role_array) {
role_array = JSON.parse(role_array);
$('#permissionsButton').click();
$('#roles-selected').empty();
$('#roles-available').empty();
$('#permission_id').val(id);
$.each(role_array['permission_roles'], function (key, value) {
$('#roles-selected').append("<option value='" + value.id + "'>" + value.name + "</option>");
});
$.each(role_array['diff_roles'], function (key, value) {
$('#roles-available').append("<option value='" + value.id + "'>" + value.name + "</option>");
})
$("select[id^='roles-']").multiselect({
search: {
left: '<input type="text" name="q" class="form-control" placeholder="Search..." />',
right: '<input type="text" name="q" class="form-control" placeholder="Search..." />',
},
fireSearch: function (value) {
return value.length > 3;
}
});
},
error: function (xhr, error, thrown) {
console.log(error);
}
});
};
function editPermission(id) {
var id = id;
$.ajax({
type: "POST",
url: "ajax/permission_getdata.php",
data: {"permission_id": id, "csrf_token": $('meta[name="csrf_token"]').attr("value")},
beforeSend: function () {
$.LoadingOverlay('show', {
image: '../login/images/Spin-0.8s-200px.svg',
imageAnimation: false,
imageColor: '#428bca',
fade: [200, 100]
});
},
complete: function () {
$.LoadingOverlay("hide");
},
success: function (response) {
var respdata = JSON.parse(response);
$("#editPermissionForm").trigger("reset");
$("#edit_permission_id").val(respdata.id);
$("#edit_PermissionName").val(respdata.name);
$("#edit_PermissionDescription").val(respdata.description);
$("#edit_PermissionCategory").val(respdata.category);
$('#editPermission').modal('show');
},
error: function (xhr, error, thrown) {
console.log(error);
}
});
}
$('#saveRoles').click(function () {
var sendData = new FormData();
var formData = [];
var new_roles = [];
var id = $('#permission_id').val();
$('#roles-selected > option').each(function () {
new_roles.push($(this).val());
});
formJson = JSON.stringify(new_roles);
sendData.append('formData', formJson);
sendData.append('permissionId', id);
sendData.append('csrf_token', $('meta[name="csrf_token"]').attr("value"));
$.ajax({
type: "POST",
url: "ajax/permission_updateroles.php",
processData: false,
contentType: false,
data: sendData,
beforeSend: function () {
$.LoadingOverlay('show', {
image: '../login/images/Spin-0.8s-200px.svg',
imageAnimation: false,
imageColor: '#428bca',
fade: [200, 100]
});
},
complete: function () {
$.LoadingOverlay("hide");
},
success: function (response) {
response = JSON.parse(response);
permissionTable.ajax.reload();
$('#permissionsModal').modal('toggle');
},
error: function (xhr, error, thrown) {
console.log(error);
}
});
});
/****************************/
/* DATATABLE INITIALIZATION */
$(document).ready(function () {
permissionTable = $('#permissionList').DataTable({
dom: "<'row'<'col-sm-3'l><'col-sm-6 text-center'B><'col-sm-3'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
order: [[3, "asc"], [1, "asc"]],
columns: [
{
name: "id",
visible: true,
searchable: false,
sortable: false,
render: function (data, type, row) {
return "";
}
},
{
name: "name",
searchable: true
},
{
name: "description",
searchable: true
},
{
name: "category",
searchable: true
},
{
name: "assign roles",
width: "90px",
searchable: false,
render: function (data, type, row) {
return "<button id='rolesbtn_" + row[0] + "' class='btn btn-info'>Assign roles</button>"
}
},
{
name: "edit permission",
width: "40px",
searchable: false
}
],
columnDefs: [{
className: 'select-checkbox',
targets: 0
}],
paging: true,
ajax: {
url: "ajax/permissions_getall.php?csrf_token=" + $('meta[name="csrf_token"]').attr("value"),
error: function (xhr, error, thrown) {
alert(xhr.responseJSON.Error);
}
},
scrollY: "600px",
scrollCollapse: true,
lengthMenu: [[15, 30, -1], [15, 30, "All"]],
select: {
style: "multi",
selector: 'td:first-child'
},
buttons: [
{
extend: 'selectAll',
className: 'selectall',
action: function (e) {
e.preventDefault();
permissionTable.rows({page: 'current'}).select();
permissionTable.rows({search: 'removed'}).deselect();
}
},
"selectNone",
{
text: 'Add New Permission',
action: function (e, dt, node, config) {
$('#newPermission').modal('show');
},
className: "btn-success"
},
{
text: 'Delete Selected',
action: function (e, dt, node, config) {
var selected_array = dt.rows({selected: true}).data();
if (confirm("Are you sure you want to delete the selected permissions?")) {
for (var i = 0, len = selected_array.length; i < len; i++) {
deletePermission(selected_array[i][0], 'rolesbtn_' + selected_array[i][0]);
}
}
},
className: "btn-danger"
}
]
}).on("select", function () {
//console.log("selected");
});
});
/****************************/
function deletePermission(id, btn_id) {
var idJSON = "[" + JSON.stringify(id) + "]";
$.ajax({
type: "POST",
url: "ajax/permissions_delete.php",
data: {"ids": idJSON, "csrf_token": $('meta[name="csrf_token"]').attr("value")},
async: false,
success: function (resp) {
permissionTable.row($('#' + btn_id).parents('tr')).remove().draw();
},
error: function (err) {
console.log(err);
alert(err.responseText);
}
});
}
$("#newPermissionForm").submit(function (event) {
event.preventDefault();
var permissionName = $("#new_PermissionName").val();
var permissionDescription = $("#new_PermissionDescription").val();
var permissionCategory = $("#new_PermissionCategory").val();
$.ajax({
url: "ajax/permissions_add.php",
type: "POST",
data: {
"permissionName": permissionName,
"permissionDescription": permissionDescription,
"permissionCategory": permissionCategory,
"csrf_token": $('meta[name="csrf_token"]').attr("value")
},
beforeSend: function () {
$.LoadingOverlay('show', {
image: '../login/images/Spin-0.8s-200px.svg',
imageAnimation: false,
imageColor: '#428bca',
fade: [200, 100]
});
},
complete: function (resp) {
$.LoadingOverlay("hide");
},
success: function (response) {
permissionTable.ajax.reload();
$("#newPermission").modal('hide');
$("#newPermissionForm")[0].reset();
},
error: function (err) {
console.log(err);
}
});
});
$("#editPermissionForm").submit(function (event) {
event.preventDefault();
var permissionId = $("#edit_permission_id").val();
var permissionName = $("#edit_PermissionName").val();
var permissionDescription = $("#edit_PermissionDescription").val();
var permissionCategory = $("#edit_PermissionCategory").val();
$.ajax({
url: "ajax/permission_update.php",
type: "POST",
data: {
"permissionId": permissionId,
"permissionName": permissionName,
"permissionDescription": permissionDescription,
"permissionCategory": permissionCategory,
"csrf_token": $('meta[name="csrf_token"]').attr("value")
},
beforeSend: function () {
$.LoadingOverlay('show', {
image: '../login/images/Spin-0.8s-200px.svg',
imageAnimation: false,
imageColor: '#428bca',
fade: [200, 100]
});
},
complete: function (resp) {
$.LoadingOverlay("hide");
},
success: function (response) {
permissionTable.ajax.reload();
$("#editPermission").modal('hide');
$("#editPermissionForm")[0].reset();
},
error: function (err) {
console.log(err);
}
});
});
//Role assignment box button logic
(function () {
$('#btnRight').click(function (e) {
var selectedOpts = $('#roles-available option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#roles-selected').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
$('#btnAllRight').click(function (e) {
var selectedOpts = $('#roles-available option');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#roles-selected').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
$('#btnLeft').click(function (e) {
var selectedOpts = $('#roles-selected option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#roles-available').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
$('#btnAllLeft').click(function (e) {
var selectedOpts = $('#roles-selected option');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#roles-available').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
}(jQuery));
// Converts array to object
function toObject(arr) {
var rv = {};
for (var i = 0; i < arr.length; ++i)
rv[i] = arr[i];
return rv;
}
});
Here is a image of the page with the button that is causing problems circled:
Here is what I have tried so far:
Attempted to move the function editPermission around as well as placing it inside the $(document).ready
I have noticed that when I click it in Chrome it seems to open a new page where it executes the script. Sort of weird. Screenshot (Normal page file circled):
What things can I try to solve this?

kendo ui grid sortable and crud is not working

I have followed this tutorial and brought up the sorting to work but now the crud operation is not working.
If i remove the grid sortable code then the crud is working, but no sort.
I have no idea where i am making mistake to make both sort and crud to work
THis is the code i have
$(document).ready(function () {
function dataSource_change(e) {
var data = this.data();
console.log(data.length); // displays "77"
}
var dataSource = new kendo.data.DataSource({
//pageSize: 20,
transport:{
read:{
url: function() {
return "/makes"},
dataType: "json",
cache: false
},
update: {
url: function (make) {
console.log(make)
return "/makes/"+ make.models[0].id
},
type: "PUT",
dataType: "json",
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token',jQuery('meta[name="csrf-token"]').attr("content")); }
},
destroy: {
url: function (make) {
return "/makes/"+ make.models[0].id
},
type: "DELETE",
dataType: "json"
},
create: {
url: "/makes",
type: "POST",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
console.log(options)
return{"make": options.models[0]};
}
else{
return {"make":options};
}
}
},
batch: true,
schema: {
model: {
id: "id",
fields: {
id: { editable: false, nullable: true },
name: { validation: { required: true } },
}
}
}
});
dataSource.bind("change", dataSource_change);
dataSource.fetch();
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
pageable: false,
height: 550,
toolbar: [{name: "create", text: "Add New Make"}],
columns: [
{ field:"name",title:"Makes" },
{ command: ["edit", "destroy"], title: "Action", width: "250px" }],
editable: "inline"
}).data("kendoGrid");
grid.table.kendoSortable({
filter: ">tbody >tr",
hint: $.noop,
cursor: "move",
placeholder: function(element) {
return element.clone().addClass("k-state-hover").css("opacity", 0.65);
},
container: "#grid tbody",
change: function(e) {
console.log(grid)
var skip = grid.dataSource.skip(),
oldIndex = e.oldIndex + skip,
newIndex = e.newIndex + skip,
data = grid.dataSource.data(),
dataItem = grid.dataSource.getByUid(e.item.data("uid"));
var updated_order = []
$('tbody tr').each(function(i){
updated_order.push({ name: $(this).children('td:first').text(), position: i+1 });
});
controller_name = $('#controller_name').val();
$.ajax({
type: "PUT",
url: '/sort',
data: { order: updated_order, controller_name: controller_name }
});
grid.dataSource.remove(dataItem);
grid.dataSource.insert(e.newIndex, dataItem);
}
});
});

How to add new tags in select2?

I am trying to get the tags from my api. Everything works fine but I cant able to add new tags. Here is what i tried:
$(function(){
var user_email = localStorage.getItem('email');
var api = localStorage.getItem("user_api_key");
var auth = "apikey" +' ' +(user_email+":"+api);
$('#s2id_id_add-places').select2({
multiple: true,
tags: [],
tokenSeparators: [",", " "],
width: "200px",
ajax: {
placeholder: "Click to enter who",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", auth);
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","application/json");
},
url: "https://example.com/api/v3/places/",
dataType: "json",
contentType: "application/json",
processData: true,
quietMillis: 50,
data: function(term) {
return {
term: term
};
},
results: function(data) {
var results = [];
if(data.objects.length > 0) {
for (i=0; i<data.objects.length; i++) {
results.push({id: data.objects[i].id, text: data.objects[i].label, isNew: true});
}
}
return {
results: results
};
},
});
});
By using the above code, I can only get the tags but I cant able to add the new tags. how can i add the new tags?
Please help
$("#e11_2").select2({
createSearchChoice: function(term, data) {
if ($(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
},
multiple: true,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});
You have to create a function like createSearchChoice, that returns a object with 'id' and 'text'. In other case, if you return undefined the option not will be created.

Jquery autocomplete is not working with dynamically added row

On click on #add I am calling add_table_row() to add new row in table
<tr class="item" id="item1">
<td><input type="text" name="billProductList[0].product.name"
id="billProductList_0__product_name" class="name></td>
..............
</tr>
Each row in similar to above one only the numbers are incremented by one.
For first .name jquery autocomplete is working properly but for dynamically added row it is not working
function add_table_row() {
var t = $('.table .item:last').attr('id');
var prs = t.slice(4);
var num1 = parseInt(prs) + 1;
var dataString = 'rowId=' + num1;
$.ajax({
type: "POST",
url: "getNewBillRow",
data: dataString,
dataType: "html",
success: function(data) {
$(".table .item:last").after(data);
}
});
}
$(document).on('click', '#add', function(event) {
event.preventDefault();
add_table_row();
});
$(".name").autocomplete({
source: function(request, response) {
$.ajax({
url: "ProductByName",
dataType: "json",
data: {
name: request.term,
maxRows: 12
},
success: function(data) {
response($.map(data.productList, function(item) {
console.log(item);
return {
label: item.name,
value: item.name,
id: item.id,
desc: item.desc,
}
}));
},
error: function(data) {
console.log(typeof data);
}
});
},
minLength: 1,
select: function(event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
var pid = $(this).parents('.item').attr('id');
//alert(ui.item.id + " " + ui.item.desc);
$("#" + pid + " .id").val(ui.item.id);
$("#" + pid + " .description").val(ui.item.desc);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
How to make it to work for all .name .
This is because when you bind autocomplete() to .name, the other controls (dynamic controls) doesn't exist in the DOM. So you need to rebind the function after adding the control to the DOM.
You can do something like this:
function BindAutoComplete() {
$(".name").autocomplete({
source: function(request, response) {
$.ajax({
url: "ProductByName",
dataType: "json",
data: {
name: request.term,
maxRows: 12
},
success: function(data) {
response($.map(data.productList, function(item) {
console.log(item);
return {
label: item.name,
value: item.name,
id: item.id,
desc: item.desc,
}
}));
},
error: function(data) {
console.log(typeof data);
}
});
},
minLength: 1,
select: function(event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
var pid = $(this).parents('.item').attr('id');
//alert(ui.item.id + " " + ui.item.desc);
$("#" + pid + " .id").val(ui.item.id);
$("#" + pid + " .description").val(ui.item.desc);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
}
Then in your ajax call :
function add_table_row() {
var t = $('.table .item:last').attr('id');
var prs = t.slice(4);
var num1 = parseInt(prs) + 1;
var dataString = 'rowId=' + num1;
$.ajax({
type: "POST",
url: "getNewBillRow",
data: dataString,
dataType: "html",
success: function(data) {
$(".table .item:last").after(data);
BindAutoComplete();
}
});
}
After you add the new row, you need to initialize autocomplete on the newly added .name field.
success: function(data) {
$(".table .item:last").after(data);
$(".table .item:last .name").autocomplete({
source: function(request, response) {
$.ajax({
url: "ProductByName",
dataType: "json",
data: {
name: request.term,
maxRows: 12
},
success: function(data) {
response($.map(data.productList, function(item) {
console.log(item);
return {
label: item.name,
value: item.name,
id: item.id,
desc: item.desc,
}
}));
},
error: function(data) {
console.log(typeof data);
}
});
},
minLength: 1,
select: function(event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
var pid = $(this).parents('.item').attr('id');
//alert(ui.item.id + " " + ui.item.desc);
$("#" + pid + " .id").val(ui.item.id);
$("#" + pid + " .description").val(ui.item.desc);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
}

Categories

Resources