I'm creating a Django site, on a certain template i added an Ajax form and i would like to add an autocomplete feature, in order to make navigation easier.
My main problem is that the data i should search is a JSON array of objects, while most of the solutions i found work with normal arrays.
Here is what i have now:
<script>
$(document).ready(function(){
// Defining the local dataset
$.getJSON('http://127.0.0.1:8000/myapi/', function(data) {
console.log(data)
//Autocomplete
});
});
</script>
<input type="text" id='firstfield' name='input_val'>
This is what the data looks like, it's around 700 records; here are the first three:
"results": [
{
"item": "First",
"id": "1847",
},
{
"item": "Second",
"id": "4442",
},
{
"item": "Third",
"id": "3847",
}]
I need this to be as fast as possible. Is there a JQuery/Ajax native solution for this? Or is there a specific library to do this? Any advice or solution is appreciated, thanks in advance!
You could use the jQuery Typeahead Search plugin. Just set-up your form to use the proper nesting of classes as seen below.
$(() => {
//$.getJSON('http://127.0.0.1:8000/myapi/', function(data) {
let data = {
"results": [
{ "item": "First", "id": "1847" },
{ "item": "Second", "id": "4442" },
{ "item": "Third", "id": "3847" }
]
};
$('#first-field').typeahead({
source: {
data: data.results.map(record => record.item)
},
callback: {
onInit: function($el) {
console.log(`Typeahead initiated on: ${$el.prop('tagName')}#${$el.attr('id')}`);
}
}
});
//})
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.js"></script>
<h1>jQuery Typeahead</h1>
<form>
<div class="typeahead__container">
<div class="typeahead__field">
<div class="typeahead__query">
<input id="first-field" name="first-field" placeholder="Search" autocomplete="off">
</div>
<div class="typeahead__button">
<button type="submit"><i class="typeahead__search-icon"></i></button>
</div>
</div>
</div>
</form>
Try this one:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
// Defining the local dataset
$.getJSON('http://127.0.0.1:8000/myapi/', function(data) {
console.log(data)
$( "#tags" ).autocomplete({
source: data
});
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
You can use Jquery autocomplete() function
Here is the link
https://jqueryui.com/autocomplete/
$( "#tags" ).autocomplete({
source: availableTags
});
} );
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure"}
Related
I'm trying to get a regular form field used for searching for an address to autocomplete its values, as seen on this page, using Leaflet Geosearch plugin.
So far the documentation says it can be binded to a form. Jquery UI's autocomplete looks like it can accomplish this, however i have not been able to wrap my head around how to do it.
I have successfully linked the form field to the geosearch provider, and it returns an array that can be seen in the browser console. I can algo get the autocomplete plugin to work, but with a local array, not the one produced by the geosearch plugin.
Here is an example of both plugins in action separately:
<!DOCTYPE html>
<html>
<head>
<title>Leaflet tests</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"></script>
<style type="text/css"> #mapid { height: 500px; width: 500px}</style>
<link rel="stylesheet" href="https://unpkg.com/leaflet-geosearch#3.0.0/dist/geosearch.css" />
<script src="https://unpkg.com/leaflet-geosearch#3.0.0/dist/geosearch.umd.js"></script>
</head>
<body>
<div id="mapid"></div>
<hr>
<div class="">
<label for="search">geosearch field (check console): </label>
<input id="search">
</div>
<div class="">
<label for="search2">autocomplete field (apple or banana): </label>
<input id="search2">
</div>
<script type="text/javascript">
//code for generating map below
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap',
subdomains: ['a','b','c']
}).addTo(mymap);
//code for search form below
const providerform = new GeoSearch.OpenStreetMapProvider();
const input = document.querySelector('input[id="search"]');
input.addEventListener('input', async (event) => {
const results = await providerform.search({ query: input.value });
console.log(results[0]); // » [{}, {}, {}, ...]
});
//
let fruits = ['Apple', 'Banana']
$("#search2").autocomplete(
{
source: fruits,
delay: 100,
minLength: 1
});
</script>
</body>
</html>
I'd greatly appreciate any pointers in the right direction on how to get the autocomplete to work with the geosearch provider.
This should work, but I don't know how to check at the moment because https://nominatim.openstreetmap.org/ is currently not working.
$('#search2').autocomplete({
source(request, response) {
const providerform = new GeoSearch.OpenStreetMapProvider({
params: {
limit: 5
}
});
return providerform.search({ query: request.term }).then(function (results) {
response(results);
});
},
delay: 100,
minLength: 1
});
Here's one basic example using jquery, there are other options too
const input = document.querySelector('input[id="search2"]');
input.addEventListener('input', async (event) => {
const results = await providerform.search({ query: input.value });
console.log(results[0]); // » [{}, {}, {}, ...]
});
let fruits = ['Apple', 'Banana']
$("#search2").autocomplete(
{
source: fruits,
delay: 100,
minLength: 1
});
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="//code.jquery.com/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<hr>
<h1> Autocomplerde demo </h1>
<div class="">
<label for="search2">autocomplete field (apple or banana): </label>
<input id="search2">
</div>
<script type="text/javascript">
</script>
</body>
</html>
i want to remove item from jquery-ui autocomplete rendered list
let say the item is compton
Question: i want to remove item "compton" once it is rendered from outside NOT from helper functions like select,create,open etc
Below is my code:
$(function() {
var availableTags = [
"john",
"khair",
"compton",
"Jordan",
"Micheal",
"Peter"
];
$( "#tags" ).autocomplete({
source: availableTags
}).focus(function () {
$("#tags").autocomplete("search");
});
// logic to remove item "compton" must reflect in rendered ui
});
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="ui-widget">
<label for="tags">Search: </label>
<input id="tags">
</div>
Try using option method which sets one or more options for the autocomplete.
$(function() {
var availableTags = [
"john",
"khair",
"compton",
"Jordan",
"Micheal",
"Peter"
];
$("#tags").autocomplete({
source: availableTags
}).focus(function() {
$("#tags").autocomplete("search");
});
$("#tags").autocomplete("option", "source", availableTags.filter(i => i !== "compton"));
});
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="ui-widget">
<label for="tags">Search: </label>
<input id="tags">
</div>
My autocomplete works only on the condition that the Page is reloaded. If I navigate to the page through a link this does not work. I have inluded the source code and a demo I have used. In the demo I have changed the var data field in order to show the values I'm fetching in the application.
Note: This is for a Ruby on Rails application.
Can someone say what is wrong with this?
<script>
$(function() {
var doctors = <%== #doctors %>;
var data = doctors.map(function (a) {
return { label: a[0], id: a[1] };
});
$('#tags').autocomplete({
delay: 0,
source: data,
select: function(event, ui) {
$('#doctor_id').val(ui.item.id);
}
});
} );
</script>
HTML code:
<div class="row">
<div class="input-field col s12 m6">
<i class="material-icons prefix">textsms</i>
<label class="active" for="tags">Doctor</label>
<input id="tags" type="text" class="autocomplete" required/>
<input id="doctor_id" name="doctor_id" type="hidden" required/>
</div>
</div>
Demo : JSfiddle
i tried your code with the correct scripts it runs just fine have a look
here is the head part
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
here is your fiddle script
var data = [
{label: "Ann Perera", id: 1},
{label: "Sam Perera", id: 2},
{label: "John Perera", id: 3}
];
$('#tags').autocomplete({
delay: 0,
source: data,
select: function(event, ui) {
$('#doctor_id').val(ui.item.label);
}
});
} );
I'm trying to display JSON results using DataTables, however I get blank table in the end. When I check browser console logs, I can see array of objects is being passed to display function but after that, nothing happens.
HTML Part:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="functions.js"></script>
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"></script>
<div class="container">
<form>
<div class="form-group row">
<label for="foodLabel" class="col-sm-2 col-form-label">Search For Food Label</label>
<div class="col-sm-10">
<input class="form-control" type="search" id="foodLabel">
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-default" type="submit" id="submit" onclick="getFormData(); return false;">Submit</button>
</div>
</div>
</form>
</div>
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
</table>
</body>
</html>
JS Part:
function getFormData(){
var foodLabel=document.getElementById('foodLabel').value;
document.getElementById('foodLabel').value = "";
var searchURL = buildSearchURL(foodLabel);
console.log(searchURL);
$.getJSON(searchURL, function(data){
//console.log(data);
//console.log(data.list.item);
display(data.list.item);
});
}
function buildSearchURL(label){
var searchURL = "http://api.nal.usda.gov/ndb/search/?format=json&q=" + label + "&sort=n&max=25&offset=0&api_key=DEMO_KEY";
return searchURL;
}
function display(data){
console.log(data);
$(document).ready(function() {
$('#example').DataTable( {
"json": data,
"columns": [
{"item": "name"}
]
} );
} );
}
It must be something completely obvious that I'm missing here.
I managed to figure this one out, apparently, Datatables library makes a call on it's, so I changed my display function:
function display(searchURL){
//console.log(data);
$(document).ready(function() {
$('#example').DataTable( {
ajax: {
url: searchURL,
dataSrc: 'list.item'
},
columns: [
{data: "name"}
]
} );
} );
}
You can not access the variable searchURL in display function, try this:
function display(searchURL){
//console.log(data);
$(document).ready(function() {
$('#example').DataTable( {
ajax: {
url:buildSearchURL(document.getElementById('foodLabel').value),
dataSrc: 'list.item'
},
columns: [
{data: "name"}
]
} );
} );
}
I've been able to get a JSON file to load into a table fine, but I want to have multiple JSON files and change which one is loaded into the table based on which button has been pressed. I thought I could just make it change the variable data, but then the table still stays the same (I'm assuming you have to make it refresh some how?).
Also, on a side note, is it possible to have the prices have a space between them?
test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<meta name="description" content="Hello World">
<!-- Latest compiled and minified CSS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://rawgit.com/wenzhixin/bootstrap-table/master/dist/bootstrap-table.min.css">
<script src="https://rawgit.com/wenzhixin/bootstrap-table/master/dist/bootstrap-table.min.js"></script>
<script src="data1.json"></script>
<script src="data2.json"></script>
<script>
$(function () {
$('#table').bootstrapTable({
data: data_one
});
$('#data1').on('click', function(event) {
$('#table').bootstrapTable({
data: data_one
});
});
$('#data2').on('click', function(event) {
$('#table').bootstrapTable({
data: data_two
});
});
});
</script>
</head>
<body>
<header>
<div class="jumbotron">
<div class="container">
<h3>Test</h3>
</div>
</div>
</header>
<div class="container">
<div class="row">
<div class="text-center">
<a class="btn btn-large btn-success" id="data1">Data 1</a>
<a class="btn btn-large btn-success" id="data2">Data 2</a>
</div>
</div>
</div>
<div class="container">
<div class="row">
<table id="table" class="table table-bordered" data-search="true" data-show-toggle="true">
<thead>
<tr>
<th data-field="id" data-sortable="true">ID</th>
<th data-field="name" data-sortable="true">Name</th>
<th data-field="prices" data-sortable="true">Price</th>
</tr>
</thead>
</table>
</div>
</div>
<footer>
<div class="container">
<hr>
<p><small>Google didn't help me</small></p>
</div>
</footer>
</body>
</html>
data1.json:
var data_one = [
{
"id": 0,
"name": "test0",
"prices": [
"$0",
"$5"
]
},
{
"id": 1,
"name": "test1",
"prices": [
"$4",
"$1"
]
},
{
"id": 2,
"name": "test2",
"prices": [
"$2",
"$3"
]
},
];
data2.json:
var data_two = [
{
"id": 4,
"name": "test4",
"prices": [
"$1",
"$2"
]
},
{
"id": 5,
"name": "test5",
"prices": [
"$6",
"$5"
]
},
{
"id": 6,
"name": "test6",
"prices": [
"$9",
"$7"
]
},
];
You need to specify the 'load' method when updating the data in the table:
<script>
$(function () {
$('#table').bootstrapTable({ data: data_one });
$('#data1').on('click', function(event) {
$('#table').bootstrapTable('load', { data: data_one });
});
$('#data2').on('click', function(event) {
$('#table').bootstrapTable('load', { data: data_two });
});
});
</script>
For some reason you cannot initially load the data with load method, only update. You can also append data with "append" method and do lot of cool stuff. Check out the documentation here: Bootstrap Table Documentation
1) You don't need all the ready functions, just one (the functions that look like $(function () {..}).
2) Also, you're not calling the plugin on that element again when you click a button - you have to explicitly do that.
3) Finally, you've not added an event listener to your second button - you added a duplicate listener to your first button.
4) You should remove the inline onclick="data1()" and onclick="data2()" from your HTML buttons.
$(function () {
$('#table').bootstrapTable({
data: data_one
});
$('#data1').on('click', function(event) {
$('#table').bootstrapTable({
data: data_one
});
});
$('#data2').on('click', function(event) {
$('#table').bootstrapTable({
data: data_two
});
});
});
You are not integrating data2() function. You can write your code as below.
$(function () {
$('#table').bootstrapTable({
data: data_one
});
});
function data1(){
$('#table').bootstrapTable({
data: data_one
});
}
function data2(){
$('#table').bootstrapTable({
data: data_two
});
}