Can not change textbox value on autocomplete select - javascript

I want to change the textbox value on another textbox selection with autocomplete. I'm using django 1.7 and jquery 1.9
I am not good at javascript I tried alot of solutions to make autocomplete work with django but I can not change the other textbox value.
This is django code
view.by
def auto_complete(request):
search = request.GET['term']
products = Products.objects.all().filter(product_name__startswith=search)
products_serialized = serializers.serialize('json', products)
return JsonResponse(products_serialized, safe=False)
url.by
url(r'^autocomplete/$', views.auto_complete, name='Auto Complete'),
textbox
<input type="text" id="product" name="product" class="product" value="">
<input type="text" id="price" name="product" class="price" value="">
javascript function
function Complete(){
$( "#product" ).autocomplete({
select: function (e, ui) {
$("#product").val(ui.item.label);
return false;
},
minLength: 1,
source: function (request, response) {
$.ajax({
url: '/autocomplete',
data: request,
success: function (data) {
var ParsedObject = $.parseJSON(data);
response($.map(ParsedObject, function (item) {
var results = item.fields.product_name ;
return {
value: results
};
}));
},
});
}
});
}

I found the answer
function Complete(){
$( "#product" ).autocomplete({
select: function (e, ui) {
$("#product").val(ui.item.label);
return false;
},
source: function (request, response) {
$.ajax({
url: '/autocomplete',
data: request,
success: function (data) {
var ParsedObject = $.parseJSON(data);
response($.map(ParsedObject, function (item) {
var name = item.fields.product_name ;
var price = item.fields.product_price ;
var count = item.fields.product_count ;
var the_id = item.pk ;
return {
value: name,
price: price,
count: count,
the_id: the_id,
};
}));
}
});
},
minLength: 1,
autoFocus: true,
select: function ( event, ui ) {
$('#price').val( ui.item.price );
$('#count').val( ui.item.count );
$('#the_id').val( ui.item.the_id );
},
});

Related

AutoComplete: Only allow selected valued from suggested list

I have an autocomplete script which suggest a list of tags that can be chosen from our database. The user can also type a new one even if it's not suggested.
I would only like to let the user choose a suggested value from the list. This is our code:
<input id="tokenfield" class="with-border" type="text" name="tags" placeholder="Ejemplo: PHP, Google Adwords, Traducción, etc.">
<script type="text/javascript">
var action = "skill_tag_search";
$('#tokenfield').tokenfield({
autocomplete: {
source: function (request, response) {
jQuery.get(ajaxurl, {
action: action, query: request.term
}, function (data) {
data = $.parseJSON(data);
response(data);
});
},
delay: 100
},
showAutocompleteOnFocus: true
});
</script>
Did you try the change event of jQuery autocomplete?
https://api.jqueryui.com/autocomplete/#:~:text=Events-,change,-(%20event%2C%20ui%20)
Last time I solved it doing something like this.
$('#tokenfield').tokenfield({
autocomplete: {
source: function (request, response) {
jQuery.get(ajaxurl, {
action: action, query: request.term
}, function (data) {
data = $.parseJSON(data);
response(data);
});
},
delay: 100,
change: function (event, ui) {
if (!ui) {
$(tokenfield).val(//Clear the autocomplete field);
} else {
$(tokenfield).val(//Set value to the autocomplete field);
}
}
},
showAutocompleteOnFocus: true
});

jquery autocomplete, how to show all options on focous?

I have below autocomplete code, which works fine When i type one or more letters.
$("body").on('focus', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val();
$(this).autocomplete({
minLength: 0,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(".sub-cat").val(ui.item.label);
return false;
},
change: function(event, ui) {
console.log(this.value);
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
});
I would like to populate the drop down with all of the matching words from the database on just focusing the input box. That means even without typing a single word. When i just focus, the function is called, but nothing within the
function $(this).autocomplete({ is executed. Any idea why autocomplete not working when focus in on the input field?
Use below code it will work as per your requirement.
$("body input.sub-category").each(function{
$(this).on('focus', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val();
$(this).autocomplete({
minLength: 0,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(".sub-cat").val(ui.item.label);
return false;
},
change: function(event, ui) {
console.log(this.value);
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
});
});
If this is not work add status in comment.
I was able to fix by adding one more function. So there is one function executing on keyup and another one on focus.
$("body").on('keyup', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val()?$(this).val():"";
$(this).autocomplete({
minLength: 0,
autoFocus: true,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(this).val(ui.item.label);
return false;
},
change: function(event, ui) {
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
});
Above one executes on keyup and below one on focus.
$("body").on('focus', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val()?$(this).val():"";
$(this).autocomplete({
minLength: 0,
autoFocus: true,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(this).val(ui.item.label);
return false;
},
change: function(event, ui) {
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
$(this).autocomplete("search", "");
});

AutoComplete in jQuery with dynamically added elements

My requirement is to show few options when user input some characters (minimum 3) in one of input field which might be added dynamically too.
I can not load data at page loading at beginning because data is huge. There is an ajax call to get that filtered data.
The issue what I am getting is Expected identifier error on page loading at line# 2. So, could you please tell what is wrong with the below code?
$(document).on('keydown.autocomplete', 'input.searchInput', function() {
source: function (request, response) { // Line # 2
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getNames.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
How about using another approach: initialize the autocomplete when you create the input:
$(function() {
// settings for each autocomplete
var autocompleteOptions = {
minLength: 3,
source: function(request, response) {
$.ajax({
type: "GET",
url: "getNames.html",
data: { name: request.term },
success: function(data) {
response(data);
}
});
}
};
// dynamically create an input and initialize autocomplete on it
function addInput() {
var $input = $("<input>", {
name: "search",
"class": "searchInput",
maxlength: "20"
});
$input
.appendTo("form#myForm")
.focus()
.autocomplete(autocompleteOptions);
};
// initialize autocomplete on first input
$("input.searchInput").autocomplete(autocompleteOptions);
$("input#addButton").click(addInput);
});
<form id="myForm" name="myForm" method="post">
<input id="addButton" type="button" value="Add an input" />
<input name="search" class="searchInput" maxlength="20" />
</form>
jsFiddle with AJAX
The method where I am adding new input field there writing below code.
function addInput(){
// Code to append new input filed next to existing one.
$("table").find('input[id=clientId]:last').autocomplete({
source: function (request, response) {
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getName.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},
error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
}
And some where in other js which will be used to all other (static) input fields below code is used.
jQuery("input.searchInput").autocomplete({
source: function (request, response) {
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getName.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},
error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
Note :- For any autocomplete requests in dynamically added input fields, AutoComplete code of addInput() function will be called.
Thanks to #Salman and this post Enabling jQuery Autocomplete on dynamically created input fields to give me an idea.
Try this.
$("#autocompleteElement").autocomplete({
source:function (data, response) {
$ajax({
url:'your/url?name='+data.term,
success:function(data){
response(data);
}
})
}
});
This code based on jquery UI autocomplete.

jquery autocomplete 'Disable' show all terms

Hey could someone guide me out of this problem....
I successfully created the jquery autocomplete function , but my problem is that autocomplete suggestions shows all the available labels . Autocomplete is showing the results which are not even matching the search term . I mean it showing all available label . Is their any solution to show only matching labels. here is the java function.
Any help will be gladly appreciated . Thank You
$(document).ready(function () {
$("#search-title").autocomplete({
source: function ( request, response ) {
$.ajax({
url: "availabletags.json",
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response( $.map( data.stuff, function ( item ) {
return {
label: item.label,
value: item.value
};
}));
}
});
},
minLength: 2,
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
});
EDIT : - Here is the Json File
{"stuff":[ {"label" : "Dragon", "value" : "eg.com"} ,
{"label" : "testing", "value" : "eg2.com"}]}
Successful Edited Code
<script>
$(document).ready(function () {
$("#search-title").autocomplete({
source: function ( request, response ) {
$.ajax({
url: "availabletags.json",
dataType: "json",
success: function (data) {
var sData = data.stuff.filter(function(v) {
var re = new RegExp( request.term, "i" );
return re.test( v.label );
});
response( $.map( sData, function ( item ) {
return {
label: item.label,
value: item.value
};
}));
}
});
},
minLength: 2,
focus: function (event, ui) {
this.value = ui.item.label;
event.preventDefault(); // Prevent the default focus behavior.
},
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
});
</script>
Here is the change you want to make:
dataType: "json",
success: function (data) {
var sData = data.stuff.filter(function(v) {
return v.value.indexOf( request.term ) > -1;
});
response( $.map( sData, function ( item ) {
This search will be done by value. To search by label, in other words for the user's input to be compared to the label in your JSON use the following instead:
return v.label.indexOf( ........
UPDATE
To make your search case insensitive, use the following:
var re = new RegExp( request.term, "i" );
return re.test( v.label );
instead of return v.value.indexOf( request.term ) > -1;

jQuery Autocomplete can't replace only part of input value

I am trying to make autocomplete like on Github.
We have a textarea where we write in it some text. We also put -> '#' and try to auto complete a username.
When we the autocomplete script runs it removes all of the text.
My script:
function getSign(text){
var indexOfAt = text.lastIndexOf('#');
return indexOfAt;
};
function changeText(event, ui) {
var selectedElement = event.target.innerText;
var text = $(this).val();
text.replace(/#$/ , selectedElement);
$(this).val(text);
}
$(document).ready(function() {
$("textarea#autocomplite").autocomplete({
source: function(request, response) {
$.ajax({
url: "/feeds/autocomplite_search",
data: {
term: request.term.substr(getSign(request.term)+1,request.term.length-getSign(request.term)).trim()
},
success: function(data){
for(i=0; i<data.length; i++){
data[i] = '#'+data[i];
}
return response(data);
}
});
},
minLength: 2,
delay: 400,
disabled: true,
search: function() {
if ( /\s$/.test($(this).val()) ) {
$(this).autocomplete('disable');
};
},
select: changeText
});
$("textarea#autocomplite").keyup(function() {
if ( /#$/.test($(this).val()) ) {
$(this).autocomplete('enable');
};
});
});
replace does not modify the original. Reassign:
text = text.replace(/#$/ , selectedElement);

Categories

Resources