Hey I'm trying to return a message when there are no results for the users current query! I have looked all over the net and there are similar scenarios, but I can't seem to get it working with my code below!
Can anyone help me figure this out please, as I am pulling my hair out trying to fix it!
I need to maintain the ability to use the keyboard to scroll down through the results.
Thanks in advance.
HTML
<div id="search_box">
<form id="search_form" autocomplete="off" action="" onSubmit="return false;">
<input type="text" id="suggestSearchBox" value="Search by City or Hotel Name" onClick="this.value='';" />
</form>
</div>
Javascript
NOTE: The remote data source is called "dataLocCodes", which is a javascript array
// JavaScript Document
$(function() {
$("#suggestSearchBox").focus().autocomplete(dataLocCodes, {
max: 15,
selectFirst: true,
matchContains: true,
formatItem: function(row, i, max){
if (row.hotelId) {
return row.accomName + ' - ' + row.city + ' - ' + row.country;
} else {
return row.city + ' - ' + row.country;
}
}
}).result(
function(event, row, formatted) {
$("input#suggestSearchBox").val(row.city + ' - ' + row.country);
var param = row.locparam;
var encoded_url = param.replace(/ /gi,"+");
encoded_url = encoded_url.replace(/&/gi,"amp");
window.location.href = "hotels.html?location=" + encoded_url;
});
});
There are a couple of ways to handle this. You can either create a source method so that if the results from the filter are empty, you add "no results" as a value, or you handle the response event to display a message that no results where returned in your ui. If using the source method, then add a select handler to prevent No Result from being a value.
var availableTags = ['Abc', 'Def', 'ghi'];
$('#noresults').autocomplete({
source: function (request, response) {
var responses = $.ui.autocomplete.filter(availableTags, request.term);
if (responses.length == 0) responses.push('No Result');
response(responses);
},
response: function (event, ui)
{
if (ui.content.length == 0) {
console.log('No results');
}
},
select: function (event, ui) {
// don't let no result get selected
return (ui.item.value != 'No Result');
}
});
Related
I got myself stuck in a situation. I was coding a Wikipedia search tool for a personal practice project, but I've ran into a small error. When a user enters a word into the search bar, the input will be store into the data parameter of $.getJSON, then the response will return a array of title and description objects based on the word entered in the search bar. The $.getJSON function will display 5 sets of a title and it's description in a list format in the designated HTML. Simple enough, but the issue is the $.getJSON function will display the wording "undefined", then continue to display the required set of titles and descriptions. Below I have listed my JS coding for your viewing. Also, the full code can be viewed at my codepen.
Can anyone give me a heads up of what might be the issue. As $.getJSON is asynchronous, that might be the issue, but I can't quite put my finger on it. Thanks in advance!
$("#search-word").on("keydown", function(event) {
if(event.keyCode == 13) {
event.preventDefault();
var input = {search: $(this).val()};
getWikiInfo(input);
}
});//search end
function getWikiInfo(input) {
var wikipApi = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&callback=?";
var getWikipHtml = function(response) {
console.log(response);
var wikipHtml;
for(var i = 1; i < 6; i++) {
wikipHtml += '<div class="list"><h3>' + response[1][i] + '</h3><p>' + response[2][i] + '</p></div>';
}
$("#list-container").html(wikipHtml);
}
$.getJSON(wikipApi, input, getWikipHtml);
}//getWikiInfo end
You need to do minor change. Initialize wikipHtml to empty string and check if the response[1][i] is not undefined. Below is the updated code:
var wikipHtml = '';
for (var i = 1; i < 6; i++) {
if (response[1][i] !== undefined)
wikipHtml += '<div class="list"><h3>' + response[1][i] + '</h3><p>' + response[2][i] + '</p></div>';
}
This is happening because you are not initializing wikipHtml before appending to it, but I would strongly advise that you use proper DOM manipulation instead of building your HTML using string concatenation:
$("#search-word").on("keydown", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
var input = {
search: $(this).val()
};
getWikiInfo(input);
}
}); //search end
function getWikiInfo(input) {
var wikipApi = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&callback=?";
var getWikipHtml = function(response) {
var content = [0, 1, 2, 3, 4, 5].map(function(i) {
return $('<div class="list">')
.append($('<h3>').text(response[1][i]))
.append($('<p>').text(response[2][i]));
});
$("#list-container").html(content);
}
$.getJSON(wikipApi, input, getWikipHtml);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='search-word' type='text' />
<div id='list-container'></div>
i have one issue with jquery autocomplete, its working with one textbox perfect but when i create multiple textbox using jquery with same ID at that time its working for only first textbox not for another textbox .
my question is i want to create multiple textbox and implement same autocomplete data with all text box
this is my code for create textbox using jquery
var totalSelect = $('#max_player').val();
$('#competitor_box').empty();
for (var i = 1; i <= totalSelect; i++) {
var ajaxauto = '<div class="form-group col-sm-3"><label for="tournament_name">Pocker # '+i+'</label><input id="autocomplete-ajax" type="text" class="form-control" autocomplete="off"></div>';
$('#competitor_box').append(ajaxauto);
}
this code for ajax autocomplete
$('#autocomplete-ajax').autocomplete({
// serviceUrl: '/autosuggest/service/url',
lookup: countriesArray,
lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
return re.test(suggestion.value);
},
onSelect: function(suggestion) {
$('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
onHint: function (hint) {
$('#autocomplete-ajax-x').val(hint);
},
onInvalidateSelection: function() {
$('#selction-ajax').html('You selected: none');
}
});
please help me for this issue its very important for me
thanks all.
var totalSelect = $('#max_player').val();
$('#competitor_box').empty();
for (var i = 1; i <= totalSelect; i++) {
var ajaxauto = '<div class="form-group col-sm-3"><label for="tournament_name">Pocker # '+i+'</label><input class="txtAutocomplete" type="text" class="form-control" autocomplete="off"></div>';
$('#competitor_box').append(ajaxauto);
}
Autocomplete function
$('.txtAutocomplete').autocomplete({
// serviceUrl: '/autosuggest/service/url',
lookup: countriesArray,
lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
return re.test(suggestion.value);
},
onSelect: function(suggestion) {
$('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
onHint: function (hint) {
$('#autocomplete-ajax-x').val(hint);
},
onInvalidateSelection: function() {
$('#selction-ajax').html('You selected: none');
}
});
why did you use the same ID for severals input ? use classes if you have to tag multiples elements, for example .autocomplete-ajax-input on each textbox. And then declare your autocomple function with $('.autocomplete-ajax-input').autocomplete
I have the following field inside my asp.net mvc web application:-
<input class="push-up-button searchmargin" placeholder="Search by tag.." name="searchTerm2" data-autocomplete-source= "#Url.Action("AutoComplete", "Home")" type="text" style="margin-top:8px"/>
and i wrote the following autocomplete function:-
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"), minLength: 1, delay: 1000,
create: function () {
$(this).data("autocomplete")._renderItem = function (ul, item) {
return $('<li>').append('<a>' + item.label + '<br>' + item.resourcename + ' | ' + item.customername + ' | ' +item.sitename + '<hr>' +'</a>')
.appendTo(ul);
};
}
});
});
Currently the auto complete is working well (the result list will be displayed), but the problem is that if i select an item from the auto complete result it will not be rendered inside the auto complete field.and when i check the firebug i noted the following error , when selecting an auto complete item:-
TypeError: item is undefined
[Break On This Error]
self.element.val( item.value );
For example if i start typing the following words "i am" , then i select "I am writing" from the autocomplete list result , then the autocomplete field will have the "I am" text instead of the select "I am writing". Can any one advice , what is causing this problem?
Thanks
EDIT
i edited my autocomplete as follow, by adding focus & select :-
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"), minLength: 1, delay: 1000,
focus: function (event, ui) {
$("input[data-autocomplete-source]").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("input[data-autocomplete-source]").val(ui.item.label);
return false;
},
create: function () {
$(this).data("autocomplete")._renderItem = function (ul, item) {
return $('<li>').append('<a>' + '<b>'+item.label + '</b><br>' + '<span style="color:#8e8e8e ">' + item.resourcename + ' | ' + item.customername + ' | ' + item.sitename + '<hr style="padding: 0px; margin: 0px;">' + '</span></a>')
.appendTo(ul);
};
}
});
});
but i wil get the following error when i am trying to select an autocomplete item:-
TypeError: ui.item is undefined
Please add "Select" event and try below
$( "input[data-autocomplete-source]" ).autocomplete({
select: function( event, ui ) {
$( "input[data-autocomplete-source]" ).val( ui.item.yourValueProperties);
return false;
}
});
***Note : yourValueProperties= like customername ***
I am trying to implement typeahead for a city look-up for, but the field does not get updated. The city details show up, but I need to show the name in the city when a city is clicked, but when the form is sent, I need to send only the city code.
This is my HTML:
<input id="_hotelCity" class="form-control typehead" type="text" value="" placeholder="Enter city name or code " />
And this is the javascript:
$('#_hotelCity').typeahead({
source: function (query, process) {
airports = [];
map = {};
var data = (function () {
var data = null;
$.ajax({
'async': false,
'global': false,
'url': 'http://localhost/imakeway/forms/finder/iata-aero-codes.json',
'dataType': "json",
'success': function (jdata) {
data = jdata;
}
});
return data;
})();
$.each(data, function (i, airport) {
map[airport.complete_location] = airport;
airports.push(airport.city + ' ( <b>' + airport.iata_code + '</b> - ' + airport.airport_name + ') near ' + airport.complete_location);
});
process(airports);
},
updater: function (item) {
selectedairport = map[item].complete_location;
selectedairport = map[item].iata_code;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp( '(' + this.query + ')', 'gi' );
return item.replace( regex, "<strong>$1</strong>" );
},
});
Thank you for any suggestions
HTML input tag can have only one value. This value is stored internally and displays inside the field.
It seems you are using some kind of AJAX form submission.
So, your solution is to have separate variable in JS to store city code.
Another solution is to use Select2 instead of typeahead.
This is my choice when you provide a SELECT-like field but need external AJAX data source.
Btw, with Select2 you can also force user to choose only an existing value.
Look here for example: http://ivaynberg.github.io/select2/#ajax
I would suggest you to use an additional hidden field which you update aside the normal input field.
<input id="_hotelCity" class="form-control typehead" type="text" value="" placeholder="Enter city name or code " />
<input type="hidden" value="" name="city_code" />
In this hidden field you put the city code eachtime the typeahead is updated. When submitting the form your server side script can parse it (in PHP it would $_POST['city_code']).
Using typeahead, and didnt want to replace very much of your code. I ended up with this fiddle: http://jsfiddle.net/Ydtq9/2/
You will definitely want to refactor some things but the trick is to set some instance variables in the source function, and you can access them in the updater function like so
$("#_hotelCity").typeahead({
"source": function(query, process) {
this.map = ...
},
"updater": function(item) {
var city = this.map(item)
//Then you can do what you need to with the original data.
}
})
Hey guys and gals I'm having some major issues trying to get my application to work. I've been trying to hack through this and am missing the very first part which is sending the correct input value (button value) to get the ball rolling, I'm sure this is something simple but I've been having an issue getting it working. I'd appreciate it if someone could pick out the error(s) to help me along.
This is extremely easy to do in PHP, but since this is a standalone offline
app I cannot use PHP =( I need to do all my fetching and parsing in JQuery
or Javascript....
We start with a very basic form with some buttons that have unique values.
<form>
<fieldset>
<legend>Select Orders</legend>
<table id='master'></table>
</div> <!-- end input1 -->
<div>
<button name="select" type="submit" id="btnLoad" value="load">Refresh</button>
<button name="select" type="submit" id="btnJson" value="down">Download JSON</button>
<button name="select" type="submit" id="btnView" value="view">View/Enter</button>
</div>
</fieldset>
</form>
which triggers this function
$(function() {
$("form").submit(function() {
/* what obj are we recieving?
$.each($(this), function(index, obj) {
console.log('Index: ' + index + ' Obj: '+ obj);
// returns this B/S: Index: 0 Obj: [object HTMLFormElement]
});
*/
// $this.button.val() never makes it through?
queryJsonServer($(this), "class/");
return false;
});
});
I've tried things like
var button = $(this).attr("value");
var button = $('button').attr("value"); // ends up with the first buttons value,
// but never the selected or $(this).val()
$('button').click(function() { // which WILL console.log the buttons val,
console.log($(this).val()); // but will not let me turn it into a var?
return false; // ALSO this looks like it only reads the
}); // value the SECOND click?
The Mission here is to send the buttons value as a $_POST type over to a parser which will return the appropriate JSON array to be parsed, or to be stored in a Local SQLite DB.
Either way, here's the full code of the page, could someone please give me a hand, or if I need to clarify please let me know.
<?php
ini_set('display_errors', 1);
error_reporting(E_ERROR | E_PARSE);
var_export($_POST);
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title> </title>
<script src='http://www.google.com/jsapi'></script>
<script> google.load('jquery', '1.7.1'); </script>
<script>
$(function(){
$("form").submit(function()
{
/* what obj are we recieving?
$.each($(this), function(index, obj) {
console.log('Index: ' + index + ' Obj: '+ obj);
// returns this B/S: Index: 0 Obj: [object HTMLFormElement]
});
*/
$('button').click(function() {
var state = $(this).val();
return true;
});
// state is undefined. L29
console.log(state);
// $this.button.val() never makes it through?
queryJsonServer($(this), state, "class/");
return false;
});
// query json server for
function queryJsonServer(form, state, path)
{
// on first return or refresh inputs will be returrned
var view = $('input[name="orders"]:checked').val();
var url = path + "json.php?" + state; // status = button.val()
var state = $(this).attr("value"); // ends up class/json.php?undefined
// we have data, lets post to json parser and
$.getJSON(url, view, function(data)
{
$('form').unbind('submit').trigger('submit');
var items = [];
switch(state)
{
case 'load' :
$.each(data, function(index, obj) {
items.push('<tr>');
$.each(obj, function(key, val) {
items.push((key == "report_number")
? '<td class="check" ><input type="checkbox" name="' + val + '" /></td><td><label class="caps" for="'+ key +'">'+ key.replace("_", " ") +'</label><input disabled="disabled" type="text" id="' + key + '" value="' + val + '" /></td>'
: '<td><label class="caps" for="'+ key +'">'+ key.replace("_", " ") +'</label><input disabled="disabled" type="text" id="' + key + '" value="' + val + '" /></td>')
});
items.push('</tr>');
});
$('<div/>', {
'class': 'jsonOutput',
html: items.join('')
}).appendTo('#master');
break;
case 'down' :
// populate SQLite Database
break;
case 'view' :
$.each(data, function(index, obj) {
items.push('<tr>');
$.each(obj, function(key, val) {
items.push('<td><label class="caps" for="'+ key +'">'+ key.replace("_", " ") +'</label><input disabled="disabled" type="text" id="' + key + '" value="' + val + '" /></td>')
});
items.push('</tr>');
});
$('<div/>', {
'class': 'jsonOutput',
html: items.join('')
}).appendTo('#master');
break;
default:
return false;
break;
}
});
}
});
</script>
<style type="text/css">
p, ul {width:100%; text-align:left;font-size:80%;}
.reports_box {width:auto; padding:25px 20px 20px 20px;border:1px solid #91bce6;background-color:#eff5fb;}
.inputs {width:300px; font-size:15px;padding:5px;}
.check input {padding:0 !important;}
.caps {text-transform:capitalize;}
#reports_list td, #reports_list tr {padding:10px 0 10px 2px;color:#34567b;}
</style>
</head>
<body>
<div class="reports_box">
<form id='submit'>
<fieldset>
<legend>Select Orders</legend>
<table id='master'></table>
</div> <!-- end input1 -->
<div>
<button name="select" type="submit" id="btnLoad" value="load">Refresh</button>
<button name="select" type="submit" id="btnJson" value="down">Download JSON</button>
<button name="select" type="submit" id="btnView" value="view">View/Enter</button>
</div>
</fieldset>
</form>
</div> <!-- end reports_box -->
</body>
</html>
Block form submission unless triggered by a button.
When form submission is triggered by a button:
Use $(form).serialize() to serialize the form
add "&select=ButtonValue" to the serialized string
Use $.getJSON to send a get request to your server page and get a JSON object back.
FINAL EDIT: Here's a working fiddle where I use serialize correctly: http://jsfiddle.net/YYZGG/5/
(When using the code change the form action to your correct page)
$(function(){
$("form").submit(function()
{
var state;
/* what obj are we recieving?
$.each($(this), function(index, obj) {
console.log('Index: ' + index + ' Obj: '+ obj);
// returns this B/S: Index: 0 Obj: [object HTMLFormElement]
});
*/
$('button').click(function() {
state = $(this).val();
return true;
});
// state is NOW DEFINED
console.log(state);
// $this.button.val() never makes it through?
queryJsonServer($(this), state, "class/");
return false;
.......................
Also, if having trouble getting the right values, try:
$('button').on('click', function(e) {
console.log(e.target.value);
});
EDIT:
Are you sure it should'nt just be:
$("form").submit(function(e) {
var state = e.target.value;
console.log(state);
---------
Why does your submit not include a post inside it? The method your using is GET that's why it's not a POST, either use .submit() and .post() together or just use an entire different approach working all together using GET and .click() functions, but here's an example of what using .post() looks like:
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
term = $form.find( 'input[name="s"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post and put the results in a div */
$.post( url, { s: term },
function( data ) {
var content = $( data ).find( '#content' );
$( "#result" ).empty().append( content );
}
);
});
</script>
http://api.jquery.com/jQuery.post/