Jquery Ui autocomplete get city from only one country - javascript

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
}
}));
}
});
}
});
});

Related

Using the content of a variable returned by DataTables in another part of the script

How can I use the "DeviceID" in the "columns:" in another part of the script. I have tried all manner of things like re positioning some of the code but no matter what I do I can't get it to work.
I need to use the "DeviceID" as a variable in
"url: 'get_wayfinder_offline_status.php', data: { DeviceID: deviceid },"
Look at << USE THIS IN PART MARKED "HERE"
$(document).ready(function() {
var table = $('#WayFinderStatusTable').DataTable({
ordering: false,
paging: false,
searching: false,
bInfo: false,
responsive: true,
fixedHeader: true,
scrollX: false,
pageResize: true,
ajax: {
url: 'check_wayfinder_status.php',
dataSrc: ''
},
columns: [{
data: 'DisplayDescription',
"sWidth": "100%"
},
{
data: 'DeviceName',
"visible": false
},
{
data: 'MessageCount',
"visible": false
},
{
data: 'BoardOverride',
"visible": false
},
{
data: 'DeviceID',
"visible": false
}, // << USE THIS IN PART MAKED "HERE"
],
rowCallback: function(row, data, dataIndex) {
if (data.MessageCount == 2) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOn HeaderStatusWayfinderRedTextBlink');
} else if (data.BoardOverride == 1) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOverrideOn ');
$('#WayFinderStatusTable tbody').on('click', 'tr', function() {
var hotelid = "<?php echo $_SESSION['_amember_user']['hotelid'];?>";
var data = table.row(this).data();
var deviceid = data.DeviceID;
console.log("DEVICE ID", deviceid);
$.ajax({
url: 'get_wayfinder_override_status.php',
data: {
DeviceID: deviceid
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
console.log("BoardName", result);
$('#EditOverrideWayfinderRecordID').val(result[0]);
$('#EditOverrideWayfinderBoardName').val(result[1]);
var testimage = result[2];
console.log("TEST IMAGE", testimage);
$('#EditOverrideWayfinderImage').val(result[2]);
var imagepath = '../../../../conf/conf_images/override/' + hotelid + '/' + result[2];
$("#EditOverrideWayfinderLookUpCompanyImage").attr("src", imagepath);
$("#EditOverrideWayfinderImagePreview").attr("src", imagepath);
$('#EditOverrideWayfinderRoomFromDate').val(result[3]);
$('#EditOverrideWayfinderRoomFromTimeH').val(result[4]);
$('#EditOverrideWayfinderRoomFromTimeM').val(result[5]);
$('#EditOverrideWayfinderRoomToDate').val(result[6]);
$('#EditOverrideWayfinderRoomToTimeH').val(result[7]);
$('#EditOverrideWayfinderRoomToTimeM').val(result[8]);
$('#EditOverrideWayfinderPromotionName').val(result[9]);
$('#EditOverrideWayfinderHardwareID').val(result[10]);
$('#edit_wayfinder_override_data_modal').modal('show');
}
}
});
});
} else if (data.BoardOverride == "") {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOff');
}
},
});
$(document).on('click', '.WayFinderStatusTableOff', function(e) {
$('#wayfinder_override_data_modal').modal('show');
});
$(document).on('click', '.WayFinderStatusTableOn', function(e) {
console.log("OFFLINE CLICKED");
$.ajax({
url: 'get_wayfinder_offline_status.php',
data: {
DeviceID: deviceid //<<HERE
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
// DO SOMETHING
}
}
});
$('#offline_data_modal').modal('show');
});
setInterval(function() {
$('#WayFinderStatusTable').DataTable().ajax.reload();
}, 30000);
});
Based on structure of your datatables and column, clicked on a row the deviceId is find by using the method table.row( this ).data(); and next find the right index of the data.
$('#WayFinderStatusTable').on('click', 'tr', function () {
const data = table.row( this ).data();
const deviceId = data[4];
alert(deviceId + ' -> deviceid');
});

Transforming response data select2 do not working

I use select2 (v4) and use remote data. The response is correct, but processResults function do not call and select2 do not displaying anything.
$('#country').select2({
placeholder: 'Select a country',
minimumInputLength: 3,
ajax: {
url: 'https://battuta.medunes.net/api/country/search/?key=xx',
dataType: 'json',
processResults: function(data) {
var results = [];
$.each(data, function (index, country) {
results.push({
id: country.code,
text: country.name
});
});
return {
results: results
};
},
data: function(params) {
var query = {
country: params.term
}
return query;
}
},
width: 'resolve',
});
Example response from ajax request:
[
{"name": "Indonesia", "code": "Id"},
{"name": "French Polynesia", "code": "pf"}
]
Hi below is the select code for it
$('#country').select2({
placeholder: 'Select a country',
minimumInputLength: 3,
ajax: {
url: function(param){return 'https://battuta.medunes.net/api/country/search/'},
dataType: 'jsonp' ,
data: function (params) {
var query = {
country: params.term,
// callback :"?",
key:"00000000000000000000000000000000" //put your key here
}
//this is important to make sure no extra params are added becuase the api rejects anything that has wrong params
// Query parameters will be ?city=[term]&callback=?,key=
return query;
},
processResults: function(data) {
var results = [];
$.each(data, function (index, country) {
results.push({
id: country.code,
text: country.name
});
});
return {
"results":results
};
},
},
width: 'resolve',
});
and this is my fiddle showing the working country search https://jsfiddle.net/shyamjoshi/jbfrnqLd/37/

How to pass more data autocomplete ajax

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
};
}))

Calling loop variable into autocomplate select

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);
}
});

How to store id and tags in some variable using tag-it

I am using tag-it.
This code is working properly. but problem is I am not able to get its id.
I want to get both id and tag (want to store in some hidden field ) value in my server side code.
By using fieldName: "tagValues" it is attaching a hidden field with tag name like <input type="hidden" style="display:none;" value="school,college" name="tagValues">
How can I store ids??.
Below is my code.
$(document).ready(function() {
$("#myTags").tagit({
singleField: true,
allowSpaces: false,
minLength: 2,
removeConfirmation: true,
tagLimit: 2,
fieldName: "tagValues",
placeholderText: "Tag your page (max 2)",
tagSource: function(request, response) {
console.log(request + " " + response);
$.ajax({
url: "PageTagSuggestion",
data: {term: request.term},
dataType: "json",
success: function(data) {
response($.map(data.tagList, function(item) {
return {
label: item.tag,
value: item.tag,
value1: item.id
}
}
));
}
});
},
onTagLimitExceeded: function(event, ui) {
alert("You are exceeding tag limit");
},
});
});
<ul id="myTags" name="tag"></ul>

Categories