Implementing jQuery Autocomplete - javascript

So I came up with this script that ajax calls google's suggestions and JSONP returns the search results. I managed to make the results sorted but I'd like to implement jquery autocomplete instead. I've tried any possible way I could think of but haven't got any results.
Here is the a working fiddle: http://jsfiddle.net/YBf5J/
and here is the script:
$(document).ready(function() {
$('#q').keyup(retrieve);
$('#q').focus();
$('#results').show('slow');
$("#q").autocomplete(parse, {
Height:100,
width:620,
noCache: false,
selectFirst: false
});
});
function retrieve() {
$.ajax({
type: "GET",
url: 'http://suggestqueries.google.com/complete/search?qu=' + encodeURIComponent($('#q').val()),
dataType: "jsonp",
jsonpCallback: 'parse'
});
}
var parse = function(data) {
var results = "";
for (var i = 0; i < data[1].length; i++) {
results += '<li>' + '' + data[1][i][0] + '' + '</li>';
}
$('#results').html('' + results + '');
$('#results > li a').click(function(event) {
event.preventDefault();
$('#q').val($(this).html()).closest('form').submit();
});
}
And here's the simple body:
<body><input type="text" id="q"><div id="results"></div></body>
Any help is really appreciated.
Thanks alot, rallyboy.

Here is an example of using the Jquery-UI Auto complete. Taken from your code, all i did was update the auto complete source every time the data changes using this code.
var parse = function(data) {
var results = [];
for (var i = 0; i < data[1].length; i++) {
results.push(data[1][i][0]);
}
$('#q').autocomplete({
source: results
});
See fiddle
http://jsfiddle.net/WUcpC/1/
It uses just the base CSS but that can be changed by pointing it at which ever theme you want.

Related

Append ajax result to a select 2 multiple

i need to append to a select2 multiple, some results fetched from ajax. I try to achieve this result using this code:
<select name='prodotti' rows='5' multiple id='prodotti' class='select2'></select>
Here is JS
$('#close-modal').on('click', function (e) {
var id = $('#id').val();
$.ajax({
type: 'GET',
url: '/items-fattura?id=' + id,
success: function (response) {
$("#prodotti").val(response);
}
});
});
Ajax return this results:
[{"id":2,"nome":"Certificato SSL POSITIVE"}]
Can someone help me to resolve?
Use $.each to iterate through your JSON array that you receive from ajax call.
Note:- the spelling of success, you have written sucess.
success: function(data){
data = JSON.parse(data);
var toAppend = '';
$('#prodotti').empty();
$.each(data, function(i,o){
toAppend += '<option value="'+ o.nome +'">'+o.id+'</option>';
});
$('#prodotti').append(toAppend);
}
You can try this.
$.ajax({
type: 'GET',
url: '/items-fattura?id=' + id,
success: function (response) {
var $el = $("#prodotti");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", 0)
.text('Select'));
for (i = 0; i < response.length; i++) {
$el.append($("<option></option>")
.attr("value", response[i]['id'])
.text(response[i]['name']));
}
}
});
If you receiving multiple values that are separated by comma, you can use this select2 trick to set the values:
var makeArray = commanSeparatedValues.split(',');
$('#SELECT_ID').val(makeArray);
It's an nifty little cool trick that you should use when working with select2. Avoiding the loops and $.each. Hope this helps!
take a look at
https://select2.org/programmatic-control/add-select-clear-items
for adding options to a select2 by js

Value posts firstly and then only it finishes input (if clicked). needed backwards(code is corect)

I have dropdown list of country suggestions and input above. When i click on one of them - AJAX should work(and it does) and add value to #msg_native. HTML:
echo '<div class="search_native"><input type="text" name="native_input" id="native"/>';
echo "<div id='output'></div></div>";
All JQUERY :
<script type="text/javascript">
$(document).ready(function() {
$("input").keyup(function(){
$array = ['usa','france','germany'];
$input_val = $("input[name='native_input']").val();
$('#output').text('')
r = new RegExp($input_val)
for (i = 0; i < $array.length; i++) {
if ($array[i].match(r)) {
$('#output').append('<p class="match">' + $array[i] + '</p>')
}
}
});
$(document).on('click', '.match', function(){
$value = $(this).text();
$('#native').val($value);
});
});
</script>
<script type="text/javascript">
$(function() {
$('#native').change(function() {
alert('cl');
$.ajax({
type: "POST",
url: "home.php",
dataType: 'json',
encode: true,
data: {native_input: $("input[name='native_input']").val()},
cache: false,
success: function(data){
alert(data);
$("#msg_native").after(data);
}});
return false;
});
});
</script>
The problem is that the value that gets posted is only what Ive typed myself, regardless on clicked element. But I want complete value- not only typed letters...so it firstly posts value and then 'finishes' the input (if clicked)
What can you practically advice to me?
data: {native_input: $value},
returns empty string
Some of this might be debatable but I put those in place for maintainability of the code and/or to match the most recent jQuery.
Only use one document ready handler (if possible)
Remove all the global objects (put var in front of them)
Use the native id when possible as fastest selector (not $("input[name='native_input']") for instance)
use this in the event handler, not the full selector (see next item)
If I enter "France" not "france" match does not work so need to case that input to equality var $input_val = $(this).val().toLowerCase();
You start with an empty field, might be good to show the match for that - simply trigger the keyup on startup to show all the array: }).trigger('keyup'); Now they are available for your clicking.
Attach the click handler on the wrapper for the "match" elements: $('#output').on('click', '.match', function() {
Use the promise form of the ajax .done(
Create a new custom event instead of the "change" on the native. We can then trigger that event as/when needed (the real issue you describe) Example: $('#native').trigger('myMatch'); and as I use it here:
trigger the event on a full match:
if (jQuery.inArray($input_val, $array) !== -1) {
$(this).trigger('myMatch');
}
Revised code:
$(document).ready(function() {
$("#native").on('keyup', function() {
var $array = ['usa', 'france', 'germany'];
var $input_val = $(this).val().toLowerCase();
$('#output').html('');
var r = new RegExp($input_val);
for (var i = 0; i < $array.length; i++) {
if ($array[i].match(r)) {
$('#output').append('<p class="match">' + $array[i] + '</p>');
}
}
// full match entered, trigger the match
if (jQuery.inArray($input_val, $array) !== -1) {
$(this).trigger('myMatch');
}
}).on('myMatch', function() {
alert('cl');
var nativeMatch = {
native_input: $("#native").val()
};
$.ajax({
type: "POST",
url: "home.php",
dataType: 'json',
encode: true,
data: nativeMatch,
cache: false
}).done(function(data) {
alert(data);
$("#msg_native").after(data);
});
return false;
}).trigger('keyup');
$('#output').on('click', '.match', function() {
var $value = $(this).text();
$('#native').val($value).trigger('myMatch');
});
});

how to count total number of ajax response data sets inside for loop?

i am calling an ajax and output api response in textbox. I want count total number of data sets received(counteri) and display it each time i click a button. For example if i click the button first time i want to an alert display counteri=20 and next time i click button it display counteri=40 and... counteri=60.
Currently my code keeps showing 20 each time and not adding the values. could any one tell me how to fix this.Thanks
<script>
var maxnumId = null;
var counteri= null;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......"),
success: function(data) {
maxnumId = data.pagination.next_num_id;
for (var i = 0; i < 100; i++) {
$(".galaxy").append("<div class='galaxy-placeholder'><a target='_blank' href='" + data.data[i].link +"'><img class='galaxy-image' src='" + ok.images.standard_resolution.url +"' /></a></div>");
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
//alert('www!'+i);
counteri=i;
}
}
});
counteri=counteri+counteri;
alert('counteri is now: ' + counteri);
}
</script>
<body>
<br>
<center>
<div id="myDiv"></div>
<div class="galaxy"></div>
<button id="mango" onclick="callApi()">Load More</button>
</html>
EDIT:
Adding this in start of success added up total number of records from ajax response
var num_records = Object.keys(data.data).length;
num_records2=num_records2+num_records;
alert('number of records:'+ num_records2);
and
var num_records2 =null; // outside function
Ajax are async calls.
Move the alert to just after the for. Not outside the success callback.
Looks like the problem is that you are setting counteri to the value of i instead of adding the value of i. Try this instead:
counteri += i;
Ajax calls are asynchronous. You should increment your counter on success, not outside of the ajax call. Something like this:
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
maxnumId = data.pagination.next_num_id;
for (var i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri=counteri+i;
alert('counteri is now: ' + counteri);
}
});
}
Considering that your ajax request is executed with success, to get what you want you need to declare the i variable before for ( ....) loop as is the follow script:
var counteri = 0;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
var i,
maxnumId = data.pagination.next_num_id;
for (i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri=counteri+i;
alert('counteri is now: ' + counteri);
}
});
}
Please ses here demo
EDIT
Also i have rechecked if the variable i is not declared before for(...) loop and works OK. So, the only fix is to remove counter=i from for(...) loop and to change the counteri=counteri+counteri; to counteri+=i;
Take in consideration that the ajax requests produce a number of different events that you can subscribe to. Depending of your needs you can combine this events to accomplish the desired behavior. The complete list of ajax events is explained here
EDIT2
After reading your comments, i see that you need the last value of i globally,
you need to add a second global variable too keep the sum of last i during all ajax requests.
To do this, id have added a minor change to answer:
var counteri = 0,
totali =0;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
var i,
maxnumId = data.pagination.next_num_id;
for (i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri = i;
totali = totali + i;
alert('totali is now: ' + totali );
}
});
}
JSFiddle demo
EDIT 3
After your last comment, you need to add in the API response the number of returned rows. For this, you need to change for (i = 0; i < 100; i++) { to something like this:
var num_records = data.num_rows;
for (i = 0; i < num_records ; i++) {
or, without adding the number of rows in response
var num_records = Object.keys(data.data).length;
for (i = 0; i < num_records ; i++) {

Text Area interfering with Ajax Code

I am just trying to clear the text area with an id of "discussion" it clears the textbox but it does not load the data from the server with the ajax statement. When I remove the line that clears that text area it loads all the data in fine but just adds to the current data.
Here is my code:
function LoadRoomMessages(id)
{
$.ajax(
{
type: "Get",
url: "#Url.Action("GetMessages", "Home")",
data: { roomId: id },
success: function (data)
{
// Here is the line that causes issues.
$('#discussion').val('');
json = data;
var obj = JSON.parse(json);
for (var i = 0; i < data.length; i++)
{
$('#discussion').append(htmlEncode(obj[i].Author) + " : " + htmlEncode(obj[i].Message) + "\r\n");
}
}
});
}
You may also try (as you asked to answer it)
$('#discussion').empty();

How do I store multiple check boxes with local storage

So, to be honest I am going to have a hard time explaining this so I apologize in advanced.
Basically I am populating a list of checkboxes with the names of cities. using ajax. What I want to do is allow multiple checkboxes to be checked and store each checkbox value in one single key in local storage. I guess it would look something like this as an example in local storage: city: new york,Los Angeles,Miami. I have tried everything I know and I don't even know how to phrase it in google so if anyone could me that would be great. Ill post my code below.
--This is how I am currently populating the checkbox list:
$(document).delegate("#main", "pagecreate", function () {
var citySelect = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'base_city.php',
data: '',
isajax: 1,
dataType: 'json',
success: function (data) {
var $city_box = $('#city-selector');
$city_box.empty();
for (var i = 0, len = data.length; i < len; i++) {
$city_box.append("<label for='city_select'><input type='checkbox' name='city_select[]' class='citySelect' value='" + data[i].city + "'>" + data[i].city + "</label>");
}
}
});
});
--This is how I am currently storing the values:
<script type="text/javascript">
function filterForm() {
var cityNames = $('.city_select').attr('value');
localStorage.setItem("city2", JSON.stringify(cityNames));
window.location = "#main";
location.reload();
}
</script>
try to replace
$('.city_select').attr('value');
by
var arr = [];
$("input[type=checkbox].city_select:checked").each(function(){arr.push(this.value);});

Categories