jQuery Autocomplete can't replace only part of input value - javascript

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);

Related

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", "");
});

Can not change textbox value on autocomplete select

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 );
},
});

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;

How to close autocomplete dropdown on side click

I user jquery autocomplete to fetch some results and results are displayed but when I click on the side can't close dropdown with returned results.
$(function () {
$("#search").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("TestAutoComplete", "Home")', type: "POST", dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Title
};
}));
}
});
},
minLength: 1,
select: function (event, ui) {
onItemSelect(ui.item);
},
open: function () {
$(this).removeClass('ui-corner-all').addClass('ui-corner-top');
$(this).autocomplete('widget').css('z-index', 999999);
},
close: function () {
$(this).removeClass('ui-corner-top').addClass('ui-corner-all');
}
})
.data('ui-autocomplete')._renderItem = function (ul, item) {
return $('<li>')
.data('autocomplete-item', item)
.append('<p >' + item.label + "</p>")
.appendTo(ul);
};
});
Very stupid error.
$("#search").autocomplete({...
it should be
$(".search").autocomplete({...
and it work.
Your markup isn't totally clear to me from just looking at your js but it would be something like this:
$("html").on("click.autocomplete", function(e){
var $targ = $(e.target || event.srcElement);
if ( !$targ.is( /* searchlist */ ) || !$( /* searchlist */ ).has( $targ ).length ) {
//Close autocomplete
$("html").off(".autocomplete");
}
});
You leave us somehow blinded of your implementation, but assuming a good pattern the solution would be, detect on every click on the document if the element that was clicked (e.target) ) is inside the search else close the searchbox.
$(document).on('click', function(e)
{
var jqTarget = $(e.target);
if ( !jqTarget.closest('#search').length )
{
$("#search").hide();
}
});
var that = $('.autocomplete'); //Define this somewhere in the page to refer later
$('document').on('mousedown', function(e){
if ($(e.target).closest('.autocomplete:not(:visible)').length != 0) {
that.hide();
}
});

JQUERY autocomplete working in chrome and firefox but not working in IE

I am using a variable from a function to create a autocomplete functionality, here is the code:
function autocomplete(mp_info){
var request_data = {
'_action': 'GET'
};
$(mp_info).find("#id_mp_element").autocomplete({
source: function( request, response, elems ) {
alert("working");
$.ajax({
url: "/api/slots/"+request.term+"/12/",
dataType: "json",
type: 'POST',
data: request_data,
success: function( data ) {
response($.map(data, function(item) {
return {
label: item.name,
id: item.id,
pos: item.position
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
var info_row = $(".info_row").has(this);
$($('td',info_row.parent().prev())[2]).text($(".info_row #id_mp_element").val()+" / "+ui.item.pos);
$("#id_mp_s").val(ui.item.id);
$("#id_mp_position_metric").val(ui.item.pos);
},
});
}
The alert message it is not shown in IE, when we write something in the text input
remove coma at the end:
select: function( event, ui ) {
var info_row = $(".info_row").has(this);
$($('td',info_row.parent().prev())[2]).text($(".info_row #id_mp_element").val()+" / "+ui.item.pos);
$("#id_mp_s").val(ui.item.id);
$("#id_mp_position_metric").val(ui.item.pos);
} <------- there shouldn't be a come here
});

Categories

Resources