How to return jquery autocomplete result to the separate div? - jquery-ui

I've found here that to overwrite one of the autocomplete events. But can somebody please provide me with example how to do the same?

The appendTo option does indeed work as expected, and if you inspect at the DOM, the <ul> results element will be attached to the element. However, due to absolute positioning generated by jQueryUI, the list still appears directly under the <input>.
That said, you can override the internal _renderItem to directly append results to a completely different element, for example:
HTML
<input id="autocomplete"/>
<div class="test">Output goes here:<br/><ul></ul></div>
JavaScript
$('input').autocomplete({
search: function(event, ui) {
$('.test ul').empty();
},
source: ["something", "something-else"]
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li/>')
.data('item.autocomplete', item)
.append(item.value)
.appendTo($('.test ul'));
};
I have also created a demo to demonstrate this. Please note that the latest jQuery library has not had jQueryUI tested against it fully, so I am using the previous version which allows me to select to include jQueryUI directly with the jsFiddle options.

<div class="test">Output goes here:<br/></div>
<script>
$("input#autocomplete").autocomplete({
source: ["something", "something-else"],
appendTo: ".text",
position: { my: "left top", at: "left bottom", of: ".test" }
// other options here
});
</script>

I needed more control over where to put the data, so this is how I went about it:
$("#input").autocomplete({
minLength: 3,
source: [
"ActionScript",
"AppleScript",
"Asp"
],
response: function(event, ui) {
console.log(ui.content);
// put the content somewhere
},
open: function(event, ui) {
// close the widget
$(this).autocomplete('close');
}
});

hle's answer worked awesome for me and gives you more flexibility! Here is my test code that was modified by his answer:
$("#autocomplete").autocomplete({
minLength: 3,
source: ["something", "something-else"],
response: function(event, ui)
{
console.log(ui.content);
// put the content somewhere
},
open: function(event, ui)
{
// close the widget
$(this).autocomplete('close');
}
});

Although this question is pretty old but i got a pretty easy solution. No hack, nothing just in jQuery way:
Instead of autocomplete response function, just add response data in div on success
$(document).ready(function () {
$("#book-code-search").autocomplete({
minLength: 2,
delay: 500,
source: function (request, response) {
$.ajax( {
url: "server side path that returns json data",
data: { searchText: request.term, param2 : $("#type").val()},
type: "POST",
dataType: "json",
success: function( data ) {
$("#data-success").html(data.returnedData); //returnedData is json data return from server side response
/* response($.map(data, function (item) {
return {
label: item.FullDesc,
value: item.FullDesc
}
})) */
}
});
}
});
});
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id='data-success' style='color: green;'></div>
<input type='text' placeholder='Enter Book Code' id='book-code-search' />
<input type='hidden' id='type' value='book'>

Related

jQuery ui 1.10.4 vs 1.9.2 autocomplete

I use jquery ui 1.10.4 to implement the autocomplete, and it work fine.
but now i have to use the jquery ui 1.9.2, but the autocomplete will not work.
1.The search result will not display, so I add the open() and close() function to solved it. Reference by jqueryUI autocomplete menu show effect
2.But the select function not working now, it will direct to the other page before. I write a conosle.log in the select function, but it not show.
Have anyone can help me to solve it?
$("#tags").autocomplete({
enable: true,
delay: 300,
open: function () {
$('ul.ui-autocomplete').addClass('opened');
},
close: function () {
$('ul.ui-autocomplete')
.removeClass('opened')
.css('display', 'block');
},
source: function (request, response) {
// get data
},
select: function (e, ui) {
console.log('TEST');
location.href = "http://domain/Page?id=" + ui.item.data;
},
autoFocus: true
});
It should work, just change ui.item.data by ui.item.value. Don't know why your console.log doesn't work. What version of jquery core do you use?
$("#tags").autocomplete({
enable: true,
delay: 300,
open: function () {
$('ul.ui-autocomplete').addClass('opened');
},
close: function () {
$('ul.ui-autocomplete')
.removeClass('opened')
.css('display', 'block');
},
source: ['apple','banana','orange'],
select: function (e, ui) {
alert(ui.item.value);
},
autoFocus: true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"/>
<input id="tags" name="tags" type="text"/>

jquery-ui autocomplete position

I am using jquery-ui autocomplete to retrieve items from a SQL database which is working fine but I would like to move the autocomplete list to another part of the page.
I have been trying to use the Position option from here but cant seem to get the correct syntax when applying to my code?
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.23/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtCity").autocomplete({
source: function (request, response) {
var param = { cityName: $('#txtCity').val() };
$.ajax({
url: "test.aspx/GetCities",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
select: function (event, ui) {
event.preventDefault();
minLength: 2//minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data.
}
});
});
</script>
I wanted to move the autocomplete box to the right hand side of the textbox.
After a nights sleep my first attempt again this morning worked fine, think I had originally only missed a comma in one of my attempts yesterday.
I just stripped it back to a basic implementation using an array instead of the ajax call and then applied the working syntax to my code.
Wasted FAR too much time on this yesterday, just shows taking a step back and time away from the screen helps work things out!
Thanks for your help
Working code for the record:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>JQuery AutoComplete TextBox Demo</title>
<link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />
</head>
<body>
<form id="form1" runat="server">
<div><h1>AutoComplete Textbox</h1>
Software
<asp:TextBox TextMode="multiline" Columns="50" Rows="5" ID="txtCity" runat="server"></asp:TextBox>
</div>
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.23/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtCity").autocomplete({
source: function (request, response) {
var param = { cityName: $('#txtCity').val() };
$.ajax({
url: "test.aspx/GetCities",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
position: {
my: "left center",
at: "right center",
},
select: function (event, ui) {
event.preventDefault();
minLength: 2//minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data.
}
});
});
</script>
</body>
</html>

Unable to access DIV element in Bootstrap Popover / Jquery autocomplete

I have a link which opens a Bootstrap popver. Inside of this popover, I have a text field that I want to use as a Jquery Autocomplete. The problem is, I am unsure how to access the Div ID for the text box that is in the popover -- using conventional methods don't work. My Autocomplete works fine on a standalone page, but not on popover. Please help!
Text: <input type="text" id="add_game_search"/></div>'>Popover
$(document).ready(function () {
$('[data-toggle="add_game"]').popover({
'trigger': 'click',
'html': 'true',
'placement': 'bottom'
});
});
$(document).ready(function () {
$('.add_game_search').autocomplete({
source: function (request, response) {
$.ajax({
global: false,
url: "http://www.google.com",
dataType: "html",
success: function (data) {
response($.map(data, function (item) {
alert("in response");
}));
}
});
}
});
});
js fiddle: http://jsfiddle.net/hwEp6/2/
simplified fs fiddle proving the concept: http://jsfiddle.net/hwEp6/3/
Here the problem is not with jQuery autocomplete or bootstrap. The actual reason is #add_game_search is generated dynamically when you click the Popover which you have not handled.
Change your code as below,
$(document).ready(function () {
$('body').on('click', '#add_game_search', function () {
alert("here");
});
});
JSFiddle

jQueryUI tooltip Widget to show tooltip on Click

How the new jQueryUI's tooltip widget can be modified to open the tooltip on click event on certain element's on document, while the others are still showing their tootip on mouseover event. In click-open case the tooltip should be closed by clicking somewhere else on the document.
Is this possible at all?
Using jqueryui:
HTML:
<div id="tt" >Test</div>
JS:
$('#tt').on({
"click": function() {
$(this).tooltip({ items: "#tt", content: "Displaying on click"});
$(this).tooltip("open");
},
"mouseout": function() {
$(this).tooltip("disable");
}
});
You can check it using
http://jsfiddle.net/adamovic/A44EB/
Thanks Piradian for helping improve the code.
This code creates a tooltip that stays open until you click outside the tooltip. It works even after you dismiss the tooltip. It's an elaboration of Mladen Adamovic's answer.
Fiddle: http://jsfiddle.net/c6wa4un8/57/
Code:
var id = "#tt";
var $elem = $(id);
$elem.on("mouseenter", function (e) {
e.stopImmediatePropagation();
});
$elem.tooltip({ items: id, content: "Displaying on click"});
$elem.on("click", function (e) {
$elem.tooltip("open");
});
$elem.on("mouseleave", function (e) {
e.stopImmediatePropagation();
});
$(document).mouseup(function (e) {
var container = $(".ui-tooltip");
if (! container.is(e.target) &&
container.has(e.target).length === 0)
{
$elem.tooltip("close");
}
});
This answer is based on working with different classes. When the click event takes place on an element with class 'trigger' the class is changed to 'trigger on' and the mouseenter event is triggered in order to pass it on to jquery ui.
The Mouseout is cancelled in this example to make everything based on click events.
HTML
<p>
<input id="input_box1" />
<button id="trigger1" class="trigger" data-tooltip-id="1" title="bla bla 1">
?</button>
</p>
<p>
<input id="input_box2" />
<button id="trigger2" class="trigger" data-tooltip-id="2" title="bla bla 2">
?</button>
</p>
jQuery
$(document).ready(function(){
$(function () {
//show
$(document).on('click', '.trigger', function () {
$(this).addClass("on");
$(this).tooltip({
items: '.trigger.on',
position: {
my: "left+15 center",
at: "right center",
collision: "flip"
}
});
$(this).trigger('mouseenter');
});
//hide
$(document).on('click', '.trigger.on', function () {
$(this).tooltip('close');
$(this).removeClass("on")
});
//prevent mouseout and other related events from firing their handlers
$(".trigger").on('mouseout', function (e) {
e.stopImmediatePropagation();
});
})
})
http://jsfiddle.net/AK7pv/111/
I have been playing with this issue today, I figured I would share my results...
Using the example from jQueryUI tooltip, custom styling and custom content
I wanted to have a hybrid of these two. I wanted to be able to have a popover and not a tooltip, and the content needed to be custom HTML. So no hover state, but instead a click state.
My JS is like this:
$(function() {
$( document ).tooltip({
items: "input",
content: function() {
return $('.myPopover').html();
},
position: {
my: "center bottom-20",
at: "center top",
using: function( position, feedback ) {
$( this ).css( position );
$( "<div>" )
.addClass( "arrow" )
.addClass( feedback.vertical )
.addClass( feedback.horizontal )
.appendTo( this );
}
}
});
$('.fireTip').click(function () {
if(!$(this).hasClass('open')) {
$('#age').trigger('mouseover');
$(this).addClass('open');
} else {
$('#age').trigger('mouseout');
$(this).removeClass('open');
}
})
});
The first part is more or less a direct copy of the code example from UI site with the addition of items and content in the tooltip block.
My HTML:
<p>
<input class='hidden' id="age" />
Click me ya bastard
</p>
<div class="myPopover hidden">
<h3>Hi Sten this is the div</h3>
</div>
Bacially we trick the hover state when we click the anchor tag (fireTip class), the input tag that holds the tooltip has a mouseover state invoked, thus firing the tooltip and keeping it up as long as we wish... The CSS is on the fiddle...
Anyways, here is a fiddle to see the interaction a bit better:
http://jsfiddle.net/AK7pv/
This version ensures the tooltip stays visible long enough for user to move mouse over tooltip and stays visible until mouseout. Handy for allowing the user to select some text from tooltip.
$(document).on("click", ".tooltip", function() {
$(this).tooltip(
{
items: ".tooltip",
content: function(){
return $(this).data('description');
},
close: function( event, ui ) {
var me = this;
ui.tooltip.hover(
function () {
$(this).stop(true).fadeTo(400, 1);
},
function () {
$(this).fadeOut("400", function(){
$(this).remove();
});
}
);
ui.tooltip.on("remove", function(){
$(me).tooltip("destroy");
});
},
}
);
$(this).tooltip("open");
});
HTML
Test
Sample: http://jsfiddle.net/A44EB/123/
Update Mladen Adamovic answer has one drawback. It work only once. Then tooltip is disabled. To make it work each time the code should be supplement with enabling tool tip on click.
$('#tt').on({
"click": function() {
$(this).tooltip({ items: "#tt", content: "Displaying on click"});
$(this).tooltip("enable"); // this line added
$(this).tooltip("open");
},
"mouseout": function() {
$(this).tooltip("disable");
}
});
jsfiddle
http://jsfiddle.net/bh4ctmuj/225/
This may help.
<!-- HTML -->
Click me to see Tooltip
<!-- Jquery code-->
$('a').tooltip({
disabled: true,
close: function( event, ui ) { $(this).tooltip('disable'); }
});
$('a').on('click', function () {
$(this).tooltip('enable').tooltip('open');
});

How do I pass an extra parameter to Jquery Autocomplete field?

I'm using the JQuery Autocomplete in one of my forms.
The basic form selects products from my database. This works great, but I'd like to further develop so that only products shipped from a certain zipcode are returned. I've got the backend script figured out. I just need to work out the best way to pass the zipcode to this script.
This is how my form looks.
<form>
<select id="zipcode">
<option value="2000">2000</option>
<option value="3000">3000</option>
<option value="4000">4000</option>
</select>
<input type="text" id="product"/>
<input type="submit"/>
</form>
And here is the JQuery code:
$("#product").autocomplete
({
source:"product_auto_complete.php?postcode=" + $('#zipcode').val() +"&",
minLength: 2,
select: function(event, ui){
//action
}
});
This code works to an extent. But only returns the first zipcode value regardless of which value is actually selected. I guess what's happening is that the source URL is primed on page load rather than when the select menu is changed. Is there a way around this? Or is there a better way overall to achieve the result I'm after?
You need to use a different approach for the source call, like this:
$("#product").autocomplete({
source: function(request, response) {
$.getJSON("product_auto_complete.php", { postcode: $('#zipcode').val() },
response);
},
minLength: 2,
select: function(event, ui){
//action
}
});
This format lets you pass whatever the value is when it's run, as opposed to when it's bound.
This is not to complicated men:
$(document).ready(function() {
src = 'http://domain.com/index.php';
// Load the cities straight from the server, passing the country as an extra param
$("#city_id").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term,
country_id : $("#country_id").val()
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
});
jQuery("#whatJob").autocomplete(ajaxURL,{
width: 260,
matchContains: true,
selectFirst: false,
minChars: 2,
extraParams: { //to pass extra parameter in ajax file.
"auto_dealer": "yes",
},
});
I believe you are correct in thinking your call to $("#product").autocomplete is firing on page load. Perhaps you can assign an onchange() handler to the select menu:
$("#zipcode").change(resetAutocomplete);
and have it invalidate the #product autocomplete() call and create a new one.
function resetAutocomplete() {
$("#product").autocomplete("destroy");
$("#product").autocomplete({
source:"product_auto_complete.php?postcode=" + $('#zipcode').val(),
minLength: 2,
select: function(event, ui){... }
});
}
You may want your resetAutocomplete() call to be a little smarter -- like checking if the zip code actually differs from the last value -- to save a few server calls.
This work for me. Override the event search:
jQuery('#Distribuidor_provincia_nombre').autocomplete({
'minLength':0,
'search':function(event,ui){
var newUrl="/conf/general/provincias?pais="+$("#Distribuidor_pais_id").val();
$(this).autocomplete("option","source",newUrl)
},
'source':[]
});
Hope this one will help someone:
$("#txt_venuename").autocomplete({
source: function(request, response) {
$.getJSON('<?php echo base_url(); ?>admin/venue/venues_autocomplete',
{
user_id: <?php echo $user_param_id; ?>,
term: request.term
},
response);
},
minLength: 3,
select: function (a, b) {
var selected_venue_id = b.item.v_id;
var selected_venue_name = b.item.label;
$("#h_venueid").val(selected_venue_id);
console.log(selected_venue_id);
}
});
The default 'term' will be replaced by the new parameters list, so you will require to add again.
$('#product').setOptions({
extraParams: {
extra_parameter_name_to_send: function(){
return $("#source_of_extra_parameter_name").val();
}
}
})
$('#txtCropname').autocomplete('Handler/CropSearch.ashx', {
extraParams: {
test: 'new'
}
});

Resources