so I've googled, searched here, went everywhere, and I can't find an answer. I'm using jQuery UI autocomplete to search a list of item ids numbers. They can be any length from 1 - 99999.
The Issue:
When I type '2' for example, nothing happens, then I hit backspace and type '2' again and this time, anything starting with 2 appears below, and the event shows up in the "Network List" on developer's tools. Furthermore, when I search 1, only 1 shows up, but it's not performing the search it's just spitting back the input value. but when i hit backspace and type in 1 again, the search fires and I get the same results as I did with 2. Normally no matter what number I type it should just fire by default shouldn't it? How do I correct this and get my autocomplete working properly.
CODE:
$('.item-inventory').on('keyup', '#item_num', function(){
//var search = $(this);
var itemname;
var itemprice;
var itemdesc;
$(this).autocomplete({
delay : 100,
source: function(request, response){
$.ajax({
url: '../assets/server/orders/item_search.php',
dataType: 'JSON',
data: {search: request.term},
success: function (data){
var keys = data.search;
// $('#item-name').val(data.search[0].item);
// itemPrice = data.search[0].price;
// itemDesc = data.search[0].desc;
response($.map( keys, function(i){
return{
label : i.id
};
}));
}
});
},
minLength : 1
});
//$('#item-search-results').removeClass('hidden');
$(this).on('autocompleteselect', function(event, ui){
$('#item-search-results').removeClass('hidden');
});
});
Basically you are connecting the autocomplete after the first keypress (which is too late for the first keypress). You are also reconnecting it on every keypress.
You need to connect the autocomplete once at startup to any relevant element.
e.g. place this outside of the key handler:
$('.item-inventory #item_num').autocomplete({
delay : 100,
source: function(request, response){
$.ajax({
url: '../assets/server/orders/item_search.php',
dataType: 'JSON',
data: {search: request.term},
success: function (data){
var keys = data.search;
// $('#item-name').val(data.search[0].item);
// itemPrice = data.search[0].price;
// itemDesc = data.search[0].desc;
response($.map( keys, function(i){
return{
label : i.id
};
}));
}
});
},
minLength : 1
});
you can add more event keydown like here:
$('.item-inventory').on('keyup keydown', '#item_num', function(){
........
});
If not works Properly then At Page load call the autocomplete function with empty array of strings.
E.g. $("input").each(function () { $(this).autocomplete({ src: [] }); });
Now this will work at first keypress also. Best of Luck.
Please initialize the autocomplete in ready function.
Like : $(Id).autocomplete();
Related
How can I send $("#query").val()) using my Ajax function ?
If I put my Ajax call in my $(document).ready(function() , my code doesn't work anymore (the script doesn't start).
=> I can see the 'test123' string on my next page but , but if I type something in my "query" Input_Field, and then click on my link href (pointing to the same location) , the input field is reset and loose my value "query"...
Please help me :( Thank you
$(document).ready(function() {
$("#completed").live('click', function() {
alert($("#query").val());
});
$.ajax ({
url: 'http://localhost:3000/user/updateattribute',
data: { chosenformat: 'test123' , query: $("#query").val() } ,
type: 'POST',
success: function()
{
alert ('success ' );
return false; }
});
});
// do not use this anymore $(document).ready(function() {
$(function() {
event.preventDefault();
// live is no longer used use on..
$("#completed").on('click', function() {
console.log($("#query").val());
// alerts are annoying learn to use console
});
I am New to AJAX and have already asked a few question son this matter, but i have another, I use an AJAX call to auto save a value from a drop down list to database, this works great, however every time i change a value (Their are multiple drop downs with several values each can hold) I want the div to update to reflect the change in value. The AJAX I have is as follows:
<script>
$(document).ready(function(){
$('select').on('change',function () {
var statusVal = $(this).val();
var job_id = $(this).prop('id');
$.ajax({
type: "POST",
url: "saveStatus.php",
data: { statusType : statusVal, jobID: job_id },
success: function(data) {
$('#div1').load('jobs.php #div1', function() {});
}
})
});
});
</script>
So when I change a value in one drop down box (In div1) it refreshs the value, but if i was to change another value in the same or different drop down it no longer refreshs the div or saves the value to my DB, without the reload bit in my AJAX i can change the value in multple fields and it saves, but with the reload part it only happens once
-----EDIT-----
Ok further questioning, I have used
$('#div1').on( 'change', 'select', function( ) {
var statusVal = $(this).val();
var job_id = $(this).prop('id');
$.ajax({
type: "POST",
url: "saveStatus.php",
data: { statusType : statusVal, jobID: job_id },
success: function(data) {
$('#div1').load('jobs.php #div1', function() {});
}
})
});
});
and that works great even for multiple select changes. However what if I have a few selects in a few divs, EG div1, div2 and div3. How can I adapt this code to be able to refresh all divs on a change in any of the divs, or is a case of just having the code 3 times adapted for each div.
-----EDIT-----
Thankyou all, I am able to do this with
$('#div1, #div2').on( 'change', 'select', function( ) { //stuff
Ian
Your listener is bound to the select element, which I'm betting is being blown away and relaced with the load(). Check out event delegation. jQuery makes it easy. Try binding the listener on '#div1'
$('#div1').on( 'change', 'select', function( e ) { //stuff
It should then apply to the refreshed content as well.
I have jquery and jquery ui installed on my site, I have
$(document).ready(function(){
//alert('it ran');
$('.global_search').autocomplete({ source: "global_search.php", select: function( event, ui){ window.open( ui.item.url ); } });
});
and when I look in the network tab in chrome I see the result
global_search.php?term=54650 ( Note I searched for 54650 )
The response I get from that is
{"150000":{"name":"Event: TestRod08.28.2012","value":"Event: TestRod08.28.2012","link":"event_profile.php?event_id=2939"}}
Which should display "Event: TestRod08.28.2012" and on click should go to event_profile.php?event_id=2939 but the list never show's up? I have other jquery autocomplete's working on the same page and there list's are showing just fine. Any Idea's?
Try
$('#test').autocomplete({
source : function(request, callback) {
$.ajax({
url : "data.json",
datatype: 'json'
}).done(function(data) {
var results = []
$.each(data, function(key, value) {
results.push({
id : key,
label : value.name,
url: value.link
});
});
callback(results);
});
},
select : function(event, ui) {
window.open(ui.item.url);
}
});
Demo: Plunker
var options, a;
jQuery(function(){
options = { serviceUrl:'global_search.php'};
a = $('.global_search').autocomplete(options);
});
You can try that.
Found out that my global_search.php was returning a json object instead of a json array ( I had keyed values ) when I removed the key's it works just fine
Thank you everyone for your help
I am retriving Bing values from it's api through this link:
http://api.bing.net/qson.aspx?Query=s&Market=en-us&JsonType=callback&JsonCallback=
Now when I parse the results on keyup and append them in the body it works but when I set the results on jQuery's autocomplete it doesn't.
Here is the example: http://jsfiddle.net/LkVcg/
NOTE: In the fiddle I've also included Yahoo's auto suggest which uses the same method so that I can proof that it should work.
What I'm I doing wrong? How can I make the results of Bing to appear on jQuery's autocomplete()?
Here is a working version of the fiddle.
There were 2 key changes:
I set up the URL and parameters as in your "keyup" version. That fixed the 505.
You were referencing "val.key" in the "success" handler instead of "val.Text" as in your "keyup" code.
Thus:
$("#bing_auto").autocomplete({
source: function (request, response) {
console.log("source");
$.ajax({
url: "http://api.bing.net/qson.aspx?Query=" + encodeURIComponent(request.term) + "&JsonType=callback&JsonCallback=?",
dataType: "jsonp",
/*data: {
"Query": request.term,
"JsonType": "callback",
"JsonCallback" : "?"
},*/
success: function (data) {
console.log("success!");
var suggestions = [];
$.each(data.SearchSuggestion.Section, function (i, val) {
console.log("suggestion: " + val.Text);
suggestions.push(val.Text);
});
response(suggestions);
}
});
}
});
(Take out the "console.log()" calls if you like :-)
Thanks for reading this.
I am dynamically generating some data which includes a select drop-down with a text box next to it. If the user clicks the select, I am dynamically populating it (code below). I have a class on the select and I was hoping the following code would work. I tested it with an ID on the select and putting the ONE on the ID I got it to work. However, in changing the code to reference a class (since there will be multiple data groups that include a select with a text box next to it) and $(this), I could not get it to work. Any ideas would be helpful. Thanks
The relevance of the text box next to the select is the second part of the code...to update the text box when an option is selected in the select
.one is so the select is updated only once, then the .bind allows any options selected to be placed in the adjacent text box.
$('.classSelect').one("click",
function() {
$.ajax({
type: "post",
url: myURL ,
dataType: "text",
data: {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
},
success:
function(request) {
$(this).html(request); // populate select box
} // End success
}); // End ajax method
$(this).bind("click",
function() {
$(this).next().val($(this).val());
}); // End BIND
}); // End One
<select id="mySelect" class="classSelect"></select>
<input type="text">
$(this) is only relevant within the scope of the function. outside of the function though, it loses that reference:
$('.classSelect').one("click", function() {
$(this); // refers to $('.classSelect')
$.ajax({
// content
$(this); // does not refer to $('.classSelect')
});
});
a better way to handle this may be:
$('.classSelect').one("click", function() {
var e = $(this);
$.ajax({
...
success : function(request) {
e.html(request);
}
}); // end ajax
$(this).bind('click', function() {
// bind stuff
}); // end bind
}); // end one
by the way, are you familiar with the load() method? i find it easier for basic ajax (as it acts on the wrapped set, instead of it being a standalone function like $.ajax(). here's how i would rewrite this using load():
$('.classSelect').one('click', function() {
var options = {
type : 'post',
dataType : 'text',
data : {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
}
} // end options
// load() will automatically load your .classSelect with the results
$(this).load(myUrl, options);
$(this).click(function() {
// etc...
}); // end click
}); // end one
I believe that this is because the function attached to the success event doesn't know what 'this' is as it is run independently of the object you're calling it within. (I'm not explaining it very well, but I think it's to do with closures.)
I think if you added the following line before the $.ajax call:
var _this = this;
and then in the success function used that variable:
success:
function(request) {
_this.html(request); // populate select box
}
it may well work
That is matching one select. You need to match multiple elements so you want
$("select[class='classSelect']") ...
The success() function does not know about this, as any other event callback (they are run outside the object scope).
You need to close the variable in the scope of the success function, but what you really need is not "this", but $(this)
So:
var that = $(this);
... some code ...
success: function(request) {
that.html(request)
}
Thanks Owen. Although there may be a better to write the code (with chaining)....my problem with this code was $(this) was not available in the .ajax and .bind calls..so storing it in a var and using that var was the solution.
Thanks again.
$('.classSelect').one("click",
function() {
var e = $(this) ;
$.ajax({
type: "post",
url: myURL ,
dataType: "text",
data: {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
},
success:
function(request) {
$(e).html(request); // populate select box
} // End success
}); // End ajax method
$(e).one("click",
function() {
$(e).next().val($(e).val());
}); // End BIND
}); // End One