for (a = 1; a <= 2; a++) {
$("#inp-" + a + " .nama").autocomplete({
source: function(request, response) {
$.ajax({
url: "states_remote.php",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
value: item.nama,
pangkat: item.pangkat,
jabatan: item.jabatan,
nip: item.nip
};
}));
}
});
},
minLength: 2,
select: function(event, ui) {
$("#inp-" + a + " .pangkat").val(ui.item.pangkat);
$("#inp-" + a + " .nip").val(ui.item.nip);
$("#inp-" + a + " .jabatan").val(ui.item.jabatan);
$(this).next('.nama').focus();
},
html: true,
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});
}
i want use loop variable a into autocomplate select function, but i cant get access to call variable in this function
select: function(event, ui) {
$("#inp-" + a + " .pangkat").val(ui.item.pangkat);
$("#inp-" + a + " .nip").val(ui.item.nip);
$("#inp-" + a + " .jabatan").val(ui.item.jabatan);
$(this).next('.nama').focus();
},
can someone help me to solved my problem? i search in other topic maybe this name is asynchronous function.
try using a closure:-
for (a = 1; a <= 2; a++) {
(function(a) {
$("#inp-" + a + " .nama").autocomplete({
source: function(request, response) {
$.ajax({
url: "states_remote.php",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
value: item.nama,
pangkat: item.pangkat,
jabatan: item.jabatan,
nip: item.nip
};
}));
}
});
},
minLength: 2,
select: function(event, ui) {
$("#inp-" + a + " .pangkat").val(ui.item.pangkat);
$("#inp-" + a + " .nip").val(ui.item.nip);
$("#inp-" + a + " .jabatan").val(ui.item.jabatan);
$(this).next('.nama').focus();
},
html: true,
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});
})(a);
}
There is another way and i feel that would be a better one:
$(".nama").autocomplete({ // <----all the ".nama" element will be initialized
source: function(request, response) {
$.ajax({
url: "states_remote.php",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
value: item.nama,
pangkat: item.pangkat,
jabatan: item.jabatan,
nip: item.nip
};
}));
}
});
},
minLength: 2,
select: function(event, ui) {
// event.target will be the ".nama" element and
// as per your code it seems that the elements are sibling
// elements of the ".nama", so use `.end()` to get back to
// $(event.target)
$(event.target).siblings(".pangkat").val(ui.item.pangkat).end()
.siblings(".nip").val(ui.item.nip).end()
.siblings(".jabatan").val(ui.item.jabatan);
$(event.target).focus();
},
html: true,
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});
Related
I have two kendo list boxes they exchange items between them. Basically an Items available and an Items selected pair.
I have Json service which controls what items are available via a Json array.
When the user selects a new filter I want both Kendo List Boxes to clear the items out before adding the new items from the server.
Currently it appends the new list from the server to the current list.
$(document).ready(function () {
$("#filterKeyWord").click(function () {
getResults($("#keywords"));
});
$("#availableReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
connectWith: "selectedReports",
dropSources: ["availableReports"],
toolbar: {
tools: ["transferTo", "transferFrom", "transferAllTo", "transferAllFrom", "remove"]
}
});
$("#selectedReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
dropSources: ["selectedReports"],
remove: function (e) {
setSelected(e, false);
},
add: function (e) {
setSelected(e, true);
}
});
var mydata = { ReportName: "", UserId: "" };
mydata.ReportName = "SomeName";
mydata.UserId = "SomeUser";
var crudService = "",
dataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
update: {
url: crudService + "SaveReportList2",
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "post",
},
filter: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
parameterMap: function (options, operation) {
console.log(operation);
if (operation !== "read" && options.models) {
return JSON.stringify({ models: options.models });
}
if (operation === "read") {
return "request=" + JSON.stringify(mydata);
}
}
},
batch: true,
requestStart: function () {
kendo.ui.progress($(".demo-section"), true);
console.log("request start");
},
requestEnd: function () {
kendo.ui.progress($(".demo-section"), false);
console.log("request end");
},
error: function (e) {
console.log("Error" + e);
},
change: function (e) {
console.log("change" + this.data.length);
setDropDownBoxes(this);
},
schema: {
model: {
id: "ID",
fields: {
ID: { type: "number" },
Selected: { type: "boolean" },
Name: { type: "string" },
Description: { type: "string" },
InternalId: { type: "string" }
}
}
}
});
$("#saveReportList").kendoButton({
click: function (e) {
dataSource.sync();
}
});
$("#getReportList").kendoButton({
click: function (e) {
mydata.ReportName = $("#keywords").val();
dataSource.read();
}
});
function setDropDownBoxes(obj) {
var data = obj.data();
var availableReports = $("#availableReports").data("kendoListBox");
var selectedReports = $("#selectedReports").data("kendoListBox");
var items = availableReports.dataItems();
for (var i = 0; i < data.length; i++) {
if (data[i].Selected) {
selectedReports.add(data[i]);
}
else {
availableReports.add(data[i]);
}
}
}
function setSelected(e, flag) {
var removedItems = e.dataItems;
for (var i = 0; i < removedItems.length; i++) {
console.log(flag + " " + removedItems[i].ID + " " + removedItems[i].Name + " " + removedItems[i].Selected);
var item = dataSource.get(removedItems[i].ID);
item.Selected = flag;
item.dirty = !item.dirty;
}
}
});
Not sure where in your exactly the clening should be performed, but, you can use both remove() and item() methods togheter to clear a listBox.
remove() method accepts a list of li elements, which is what items() returns, so it will remove the whole li collection from the list.
var listBox = $("#listBox").data("kendoListBox");
listBox.remove(listBox.items());
Demo
I load data via an ajax call in dataInit which works and everything works fine BUT none of my columns (only dropdown columns) don't set the id value.
e.g. I have itemId and itemCode properties. I load the data and displays correctly but if I change the value in the drop down then it doesn't bind/update my itemId value.
Essentially I want the dropdown to bind to my id column thus when saving it I get an Id to save.
,{
key: false,
hidden: true,
name: 'itemId',
index: 'itemId',
editable: false
}, {
key: false,
name: 'itemCode',
index: 'itemId',
editable: true,
edittype: 'select',
editoptions: {
dataInit: function(element) {
$.ajax({
url: '#Url.Action("GetItems", "Maintenance")',
dataType: 'json',
type: 'POST',
success: function(response) {
var array = response;
if (array != null) {
var i;
for (i in array) {
if (array.hasOwnProperty(i)) {
if (itemId == array[i].id) {
$(element).append("<option value=" +
array[i].id +
" selected>" +
array[i].code +
"</option>");
} else {
$(element).append("<option value=" +
array[i].id +
">" +
array[i].code +
"</option>");
}
}
}
}
}
});
}
},
editrules: { required: true}
Here is my answer.....Look at the data events. I find the selected row and then I set the cell. The console log was just to test.
{
key: false,
hidden: true,
name: 'userId',
index: 'userId',
editable: false
}, {
key: false,
name: 'userName',
index: 'userName',
editable: true,
edittype: 'select',
editoptions: {
dataInit: function(element) {
$.ajax({
url: '#Url.Action("GetUsers", "Maintenance")',
dataType: 'json',
type: 'POST',
success: function(response) {
var array = response;
if (array != null) {
var i;
for (i in array) {
if (array.hasOwnProperty(i)) {
if (userId == array[i].id) {
$(element).append("<option value=" +
array[i].id +
" selected>" +
array[i].userName +
"</option>");
} else {
$(element).append("<option value=" +
array[i].id +
">" +
array[i].userName +
"</option>");
}
}
}
}
}
});
},
dataEvents: [
{ type: 'change',
fn: function (e) {
var rowId = $("#jqgrid").jqGrid('getGridParam', 'selrow');
$('#jqgrid').jqGrid('setCell', rowId, 'userId', $(e.target).val());
console.log($("#jqgrid").jqGrid('getCell', rowId, 'userId'));
}
}
]
}
I'm using jQueryUI autocomplete.
This is my data of a product with its respective brand details
(Laravel relationship/SQL join)
[
{
"id": 2, <--------- product.id
"name": "iphone", <--------- product.name
"created_at": "2017-02-08 06:12:34",
"updated_at": "2017-02-08 06:12:34",
"user_id": 1,
"brand_id": 1,
"ms_url": "google.com",
"gravity": 1.03,
"example_id": null,
"relevance": 210,
"brand": {
"id": 1,
"name": "apple",<--------- product.brand.name
"created_at": "2017-02-08 03:00:49",
"updated_at": "2017-02-08 03:00:49",
"user_id": 1,
"abbreviation": "AP",
"visible": 1
}
}
]
This is the ajax part of autocomplete() options. I wanted it to
fill the input with the brand and then the product name.
source: function(request, response) {
$.ajax({
type: "GET",
url: "/find",
dataType: "json",
data: {
term: request.term
},
error: function(xhr, textStatus, errorThrown) {
alert('Error: ' + xhr.responseText);
},
success: function(data) {
console.log('data: ' + data.brand.name + ' - ' + data.name);
//Outputs: apple - iphone
response($.map(data, function(product) {
return {
label: product.brand.name + " " + product.name,
value: product.brand.name + " - " + product.name
};
}))
}
});
},
select: function(event, ui) {
console.log(ui);
//only conains product.brand.name & product.name, I need product.id
// $(this).data('prod-id', ui.id);
}
Question: How can I also pass the product.id so I can add it to a data attribute on my input? I have dynamically added inputs and I wish to check the product id on the backend before submitting to the database rather than checking the input value.
Current output of input
<input type="text" class="ui-autocomplete-input" data-prod-id="" value="apple - iphone">
Desired output of input
<input type="text" class="ui-autocomplete-input" data-prod-id="2" value="apple - iphone">
You can take different value of "value" and "label" key then assign value at time of select event.
Example:
source: function(request, response) {
$.ajax({
type: "GET",
url: "/find",
dataType: "json",
data: {
term: request.term
},
error: function(xhr, textStatus, errorThrown) {
alert('Error: ' + xhr.responseText);
},
success: function(data) {
console.log('data: ' + data.brand.name + ' - ' + data.name);
//Outputs: apple - iphone
response($.map(data, function(product) {
return {
label: product.brand.name + " - " + product.name,
value: product.id //<---------- assign product id
};
}))
}
});
},
select: function(event, ui) {
$(this).val(ui.item.label); //<----------- assign value of lable
$(this).attr('data-prod-id', ui.item.value); //<------data-prod-id
return false; //<------------ to prevent from assign original value
}
I ended up going with this approach. It seems that you have to specify at least either a label, or a value. So as long as you set one of either, you can add extra necessary items into the array.
response($.map(data, function(product) {
return {
id: product.id,
title: product.brand.name + " - " + product.name,
value: product.brand.name + " " + product.name
};
}))
I have a simple select2 init which I want to be disabled by default without chaining a .select2("enable", false) afterwards.
HTML:
<input type='hidden' value="192" data-init-text='Bla bla' name="input" id="test" style="width:300px;" />
JS:
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 3,
placeholder: "Search",
enable: "false", // I want this to be working!
ajax: {
url: "http://www.weighttraining.com/sm/search",
dataType: 'jsonp',
quietMillis: 100,
data: function(term, page) {
return {
types: ["exercise"],
limit: -1,
term: term
};
},
results: function(data, page ) {
return { results: data.results.exercise }
}
},
formatResult: function(exercise) {
return "<div class='select2-user-result'>" + exercise.term + "</div>";
},
formatSelection: function(exercise) {
return exercise.term;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"term":elementText});
}
});
});
See my JSFiddle for an example. Select2 Docs here.
Simply add the disabledattribute to your input.
<input disabled type='hidden' value="192" data-init-text='Bla bla' name="input" id="test" style="width:300px;" />
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 3,
placeholder: "Search",
ajax: {
url: "http://www.weighttraining.com/sm/search",
dataType: 'jsonp',
quietMillis: 100,
data: function(term, page) {
return {
types: ["exercise"],
limit: -1,
term: term
};
},
results: function(data, page ) {
return { results: data.results.exercise }
}
},
formatResult: function(exercise) {
return "<div class='select2-user-result'>" + exercise.term + "</div>";
},
formatSelection: function(exercise) {
return exercise.term;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"term":elementText});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2.0/select2.min.js"></script>
<input disabled type='hidden' value="192" data-init-text='Bla bla' name="input" id="test" style="width:300px;" />
Try this:
Fiddle
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 3,
placeholder: "Search",
ajax: {
url: "http://www.weighttraining.com/sm/search",
dataType: 'jsonp',
quietMillis: 100,
data: function(term, page) {
return {
types: ["exercise"],
limit: -1,
term: term
};
},
results: function(data, page ) {
return { results: data.results.exercise }
}
},
formatResult: function(exercise) {
return "<div class='select2-user-result'>" + exercise.term + "</div>";
},
formatSelection: function(exercise) {
return exercise.term;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"term":elementText});
}
}).select2("enable", false);
});
I am including the latest working code below:
$("your-selector").select2({
// configuration params
}).prop("disabled", true);
Notice the prop method. Pretty simple, right?
Please visit my fiddle 1st
I am using jquery Ui auto-complete there, I want the dropdown only display(trigger) cities from a single country (like Bangladesh). How can I get that?
Here is the JavaScript approach:
$(function() {
$( ".city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
}
});
});
thanks.
You'll need to pass country code in your url. e.g. `http://ws.geonames.org/searchJSON?&country=BD'
Demo Fiddle
Updated js:
$(function() {
$( ".city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON?&country=BD",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
}
});
});