How to use jQuery autocomplete with json file? - javascript

I'm learning Ajax and jQuery and trying to use json file as data source. I'm using jQuery UI autocomplete widget to help user select one option. I know I'm terribly off the track.
My json file:
[
{"iata":"AAC", "name":"El Arish"},
{"iata":"AAE", "name":"Annabah"},
{"iata":"AAF", "name":"Apalachicola"},
{"iata":"AAG", "name":"Arapoti"},
{"iata":"AAH", "name":"Aachen"},
{"iata":"AAI", "name":"Arraias"},
{"iata":"AAJ", "name":"Awaradam"},
{"iata":"AAK", "name":"Buariki"},
{"iata":"AAL", "name":"Aalborg"},
{"iata":"AAM", "name":"Malamala"},
{"iata":"AAN", "name":"Al Ain"}
]
My JavaScript:
$(document).ready(function () {
$('#search').autocomplete({
source: function (request, response) {
var searchField = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON("beta.json", function (data) {
var output = '<ul class="searchresults">';
$.each(data, function (key, val) {
if ((val.iata.search(myExp) !== -1) ||
(val.name.search(myExp) !== -1)) {
output += '<li>';
output += '<h2>' + val.iata + '</h2>';
output += '<p>' + val.name + '</p>';
output += '</li>';
}
});
output += '</ul>';
$('#update').html(output);
});
)
});
}
});
});

I fixed some syntax errors and then wrote up this example to really get you jump started.
$( function() {
$.getJSON("http://neil.computer/stack/beta.json", function(data) {
autoComplete = [];
for (var i = 0, len = data.length; i < len; i++) {
autoComplete.push(data[i].name + ", " + data[i].iata);
}
$( "#tags" ).autocomplete({
source: autoComplete
});
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.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>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>

You can push html to an array at request, pass array to response, at .autocomplete("instance")._renderItem create an <li> element with html set to second argument item, .value property, which should be html set within request and passed to response; append <li> to first argument ul, return ul from ._renderItem
var elem = $("#search");
$.ajaxSetup({
context: elem
});
elem.autocomplete({
minLength: 1,
source: function(request, response) {
$.getJSON("beta.json")
.then(function success(data) {
var searchField = elem.val();
var myExp = new RegExp(searchField, "i");
var res = [];
$.each(data, function(key, val) {
if ((val.iata.search(myExp) !== -1) ||
(val.name.search(myExp) !== -1)) {
res.push("<h2>" + val.iata + "</h2>" + "<p>" + val.name + "</p>")
}
});
response(res);
}, function error(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown) // log `$.ajax` errors
})
}
})
.autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>", {
html: item.value
}).appendTo(ul)
};
jsfiddle http://jsfiddle.net/wr1wg5df/11/

Related

delete from database with javascript

I added a delete function to a todo list app that i built. The delete function works; however, when I refresh the page all the items that i deleted come back. How can I remove the items permanently from the database?
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
//////this section works
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
///////this does not want to remove the item from the database
$.destroy("/tasks/" + itemId, {
_method: "destroy",
task: {
done: doneValue
}
});
});
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
// still dont understand this
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
var li_to_delete = $('.todo-list li.completed');
$.ajax({
type: 'DELETE',
url: "/tasks" + li_to_delete,
success: function(){
li_to_delete.remove();
}
});
});
});
i changed the code but im not sure how to properly extract the url.

Appending content from RSS feeds to separate divs

I'm trying to display RSS using the following JS code. But when I execute this, both the RSS feeds are changed to same content (the one that is execute later) and all the feeds are appended to the same div. I think rss = this is causing the problem. Any workaround ?
HTML:
<div id="rss1" class="rss-widget">
<ul></ul>
</div>
<div id="rss2" class="rss-widget">
<ul></ul>
</div>
<div id="rss3" class="rss-widget">
<ul></ul>
</div>
JS:
function RSSWidget(id, url) {
rss = this;
rss.FEED_URL = url;
rss.JSON = new Array();
rss.widgetHolder = $('#' + id + ' ul ');
rss.storiesLimit = 15;
rss.renderBlogItem = function (object) {
var item = '<li class="blog-item">';
item += '<a href="' + object.link + '">';
item += '<div class="blog-item-title">' + object.title + '</div>';
item += '<div class="blog-item-author">' + object.author + '</div>';
// item += '<div class="blog-item-content">' + object.content + '</div>';
item += '</a>'
item += '</li>';
rss.widgetHolder.append(item);
}
return $.ajax({
url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(rss.FEED_URL),
dataType: 'json',
success: function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
rss.JSON.push({ //add objects to the array
title: e.title,
author: e.author,
content: e.content || "",
link: e.link
});
});
if (rss.storiesLimit > rss.JSON.length)
rss.storiesLimit = rss.JSON.length;
for (var i = 0; i < rss.storiesLimit; i++) {
rss.renderBlogItem(rss.JSON[i]);
}
$('#' + id + ' li ').each(function () {
var delay = ($(this).index() / rss.storiesLimit) + 's';
$(this).css({
webkitAnimationDelay: delay,
mozAnimationDelay: delay,
animationDelay: delay
});
});
}
}
});
}
$.when(RSSWidget('rss1', "http://rss.cnn.com/rss/money_markets.rss"))
.then(function () {
RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})
.then(function () {
RSSWidget('rss3', "http://finance.yahoo.com/rss/topfinstories")
});
.then(RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews"));
is immediately invoked. Try calling second RSSWidget within .then() anonymous function
.then(function() {
RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})
Also, no promise is returned from RSSWidget; you can include return $.ajax(/* settings */) from RSSWidget to return the jQuery promise object from RSSWidget.

How do I loop through a JSON list?

I have multiple items in my JSON list. I want to loop through it and display it on my page. I can't seem to get to the next object though.
{
"room":[
{"campusName":"A",
"buildingCode":"B",
"roomNumber":"208",
"times":["7-8", "9-10"]
}],
"room2":[
{"campusName":"C",
"buildingCode":"D",
"roomNumber":"208",
"times":["7-8", "9-10"
]}
]}
$(document).ready(function(){
$.getJSON("data.json", function(data){
$.each(data.room, function(){
for(var i = 0; i < data.length; i++){
$("ul").append("<li>campus: "+this['campusName']+"</li><li>building: "+this['buildingCode']+"</li><li>times: "+this.times+"</li>");
}
});
});
});
Try this
var list = '';
$.each(data, function (i, root) {
$.each(root, function (i, el) {
list += "<li>campus: " + this.campusName + "</li><li>building: " + this.buildingCode + "</li><li>times: " + this.times.join(' ') + "</li>";
});
});
$('ul').html(list);
Example
If root's has only one element in array
var list = '';
$.each(data, function (i, root) {
list += "<li>campus: " + root[0].campusName + "</li><li>building: " + root[0].buildingCode + "</li><li>times: " + root[0].times.join(' ') + "</li>";
});
$('ul').html(list);
Example
$.each(data, ..) --> Each element will be:
"room":[
{"campusName":"A",
"buildingCode":"B",
"roomNumber":"208",
"times":["7-8", "9-10"]
}]
Then, this[0] will provide the object you need to construct your li:
$.each(data, function(){
$("ul").append("<li>campus: "+this[0]['campusName']+"</li><li>building: "+this[0]['buildingCode']+"</li><li>times: "+this[0].times+"</li>");
});
Fiddle

Defining a json parsing function outside `.ajax`

Fiddle Example
I'm working on a chained selectbox that populates options via Ajax and uses localStorage to save the returned data. The code is working but I want to simplify the code a little bit.
I want to know if it's possible to define the two $.each functions as a function outside the ajax code and call it back in the success function, like this example,but the tricky part is that the returned data is defined as data in the ajax success function while it's defined as key from the localStorage.
Failed Code:
function loop(){
$.each(data.query.results.json.json, function (index, i) {
smallchoice = i.choice.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = $("<option/>").attr("value", smallchoice).text(i.bigcat + "#" +( i.cat || "") +"#" + smallchoice);
$select.append($option);
});
});
$select.dynamicDropdown({"delimiter":"#"});
}
$('select').each(function(loop){
$(this).one("mouseenter",function(){
var name = $(this).data('name'),
key = JSON.parse(localStorage.getItem(name)),
$select = $('select');var $option="";
$(this).addClass('yellow');
if (!key) {
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fcheapgamessales.com%2F133.json%22&format=json&diagnostics=true&callback=",
success: function(data){
localStorage.setItem(name, JSON.stringify(data));
loop(data);
}
});
}
else{
loop(key);
}
});
});
Original Working Code:
$('select').each(function(){
$(this).one("mouseenter",function(){
var name = $(this).data('name');
var key = JSON.parse(localStorage.getItem(name));
var $select = $('select');var $option="";
$(this).addClass('yellow')
if (!key) {
$.ajax({
url: url,
success: function(data){
localStorage.setItem(name, JSON.stringify(data));
$.each(data.query.results.json.json, function (index, i) {
smallchoice = i.choice.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = $("<option/>").attr("value", smallchoice).text(i.bigcat + "#" +( i.cat || "") +"#" + smallchoice);
$select.append($option);
});
});
$select.dynamicDropdown({"delimiter":"#"});
}
});
}
else{
$.each(key.query.results.json.json, function (index, i) {
smallchoice = i.choice.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = $("<option/>").attr("value", smallchoice).text(i.bigcat + "#" +( i.cat || "") +"#" + smallchoice);
$select.append($option);
});
});
$select.dynamicDropdown({"delimiter":"#"});
}
}); // end one function
});
Like this?
function loop(data, $select){
$.each(data.query.results.json.json, function (index, i) {
smallchoice = i.choice.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = $("<option/>").attr("value", smallchoice).text(i.bigcat + "#" +( i.cat || "") +"#" + smallchoice);
$select.append($option);
});
});
}
$('select').each(function(){
$(this).one("mouseenter",function(){
var name = $(this).data('name');
var key = JSON.parse(localStorage.getItem(name));
var $select = $('select');var $option="";
if (!key) {
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fcheapgamessales.com%2F133.json%22&format=json&diagnostics=true&callback=",
success: function(data){
localStorage.setItem(name, JSON.stringify(data));
loop(data, $select);
$select.dynamicDropdown({"delimiter":"#"});
}
});
}
else{
loop(key, $select);
$select.dynamicDropdown({"delimiter":"#"});
}
});
});

Getting index number of element of array

I have json with array of objects in it. I build my page depends on elements in this array. If there is no duplicate values of key called points, i render page with some info and description, using value of points to find this element in array. However if i have 2 and more duplicate values of key called points i render list of these elements. In this case i cant use value of points to find element in array. I know i can use index number of array element, and then pass it as parameter to my function that find and build info and description, but i'm not sure how to do that. How do i get index number of element in array?
P.S. Can provide my code if needed
Code that i'm using
var allRewards = null;
$("#reward").live('pagecreate', function(e) {
var request = $.ajax({
type: "GET",
url: "example.com/test.json"
dataType: "json",
error: function (data, textStatus){
console.log( "it`s error" );
console.log( status );
console.log( data );},
success: function (data, textStatus){
console.log( "success" );
console.log( status );
console.log( data );
}
})
request.success(function(data, textStatus){
var lis = "";
var arr = [];
var iter = 0;
allRewards = data
$.each(data.rewards, function(key, val){
if ($.inArray(val.points, arr) == -1)
{
lis += "<div data-points='"+ val.points +"'align=CENTER class = 'rewards-block ui-block-" + String.fromCharCode(97 + iter%3) + "'><a href ='#' class ='ui-link-inherit' onclick='showreward("+val.points+")'><img src ='./img/reward-icon.png'/><span>" + val.points + " pts</span></a></div>";
arr.push(val.points);
iter += 1;
}
});
$("#rewards_table").html(lis);
})
});
function showreward(point)
{
$.mobile.changePage('show-rewards.html')
console.log(allRewards);
$("#showrewards").live('pagecreate', function(e) {
var items = "";
var arr = [];
var counter = 0;
var result = $.grep(allRewards.rewards, function(e){ return e.points == point; });
if (result.length > 1)
{
$.each(result, function(key, val){
items += "<div style='color:white;'>" + val.title + "</div>"
console.log(val.title);
})
}
else if (result.length == 1)
{
// $.each(result, function(key, val){
// items += "div style='color:white;'"+ val.points + "></div>"
// console.log(val.points);
// })
$.each(result, function(key, val){
items += "<div style='background:white; padding:5px 5px 20px 5px;'><img style ='float:right; width:45%; margin-top:22px; padding: 0 0 10px 10px;' src ='" + val.main_photo_url + "'/><h3>"+ val.title + "</h3><p>" + val.description + "</p><p style='font-weight:bold; font-size:13px;'>Reedem below for " + val.points + " Zingle Points</p><table class='pagemenu' style='width:200px;'><tr><td class='width_5'><input type='submit' data-theme='w' value='Reedem Now' data-inline='true'></td><td><a data-role='button' data-icon='pagemenu-share' data-iconpos='notext' href='index.html' data-shadow='false' data-corners='false'></a></td></tr></table></div>"
});
}
console.log(items);
$("#rewards-list").html(items);
});
}
I think you're looking for Array.indexOf.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
PS. This is available in Underscore as _.indexOf.

Categories

Resources