jquery-ui autocomplete position - jquery-ui

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>

Related

Get Birthday Information using user.birthday.read scope

We have followed the steps mentioned as per the https://developers.google.com/identity/sign-in/web/server-side-flow. But while trying to fetch the date of birth information using 'scope': 'https://www.googleapis.com/auth/user.birthday.read', we are getting payload as below:
payload{"at_hash":"-mvIlEROpJsQSF9rQpRDfA","aud":"<CLIENT_ID>","azp":""<CLIENT_ID>"","email":"sample#gmail.com","email_verified":true,"exp":1628092721,"iat":1628089121,"iss":"https://accounts.google.com","sub":"108685651390298470023","name":"mnbvc plm","picture":"https://lh3.googleusercontent.com/a/AATXAJwejAC1r2SasgNdtqpd6f5q_Ih2-vDiTxELWDhg=s96-c","given_name":"mnbvc","family_name":"plm","locale":"en-GB"}
Please find below the index.html file we are using:
<!DOCTYPE html>
<html>
<head>
<meta name="google-signin-client_id" content="<CLIENT_ID>">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script src="https://apis.google.com/js/client:platform.js?onload=renderButton" async defer>
</script>
<script>
function myFunction() {
auth2.grantOfflineAccess().then(signInCallback);
}
</script>
</head>
<body>
<button onclick="myFunction()" id="signinButton">Sign in with Google</button>
<script>
function renderButton() {
gapi.signin2.render('signinButton', {
'scope': 'https://www.googleapis.com/auth/user.birthday.read',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': start
});
}
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.getAuthInstance({
client_id: '<CLIENT_ID>',
scope: 'https://www.googleapis.com/auth/user.birthday.read',
access_type: 'offline'
});
});
}
function signInCallback(authResult) {
if (authResult['code']) {
var authcode = authResult['code'];
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
// Send the code to the server
$.ajax({
type: 'POST',
url: '/gplus.form?authcode='+authcode,
// Always include an `X-Requested-With` header in every AJAX request,
// to protect against CSRF attacks.
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});
} else {
// There was an error.
}
}
</script>
</body>
</html>
What else change is required at JAVA side to get the birthday information?

Redirect before selecting an item Select2

I'm using Select2 v4.0.3 and I populate the element using ajax.
$("#el").select2({
multiple: true
maximumSelectionSize: 1,
ajax: {
url: url,
data: function (params) {
return {
name: params.term
};
},
processResults: function (data) {
return {
results: $.map(data.results, function(obj) {
return {id: obj.id, text: obj.name, key: obj.key};
}
})
};
}
}
});
I want to redirect the client before a result is selected. The problem is I need the key attribute from the clicked result. To understand better what I want to do, I paste here a snippet that works after the selection is made.
$("#el").on("select2:select", function(e) {
var selected = $(this).select2('data')[0];
location.href = base_url + '?key=' + selected.key;
});
You can use event.params.args.data.id to get the key attribute from the clicked result. So, your code would probably work like:
$("#el").on("select2:select", function(e) {
var selected = event.params.args.data.id;
location.href = base_url + '?key=' + selected;
});
I slightly modified the official Github repositories example to show my point.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<select class="js-data-example-ajax" style="width: 100%">
<option value="3620194" selected="selected">select2/select2</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: $.map(data.items, function(ghrepo) {
return {
text: ghrepo.archive_url,
id: ghrepo.archive_url
}
})
}
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
},
minimumInputLength: 1
}).on('select2:selecting', function(event, params) {
event.preventDefault();
repoId = event.params.args.data.id;
console.log(repoId);
});
</script>
</body>
</html>

Dymanic listview construction visible in jQuery Mobile 1.4.2 transition

I have a Single Page transition from #homepage to #addresses where the page #addresses include a dynamic listview build based in an $.ajax WebApi call.
The problem is that it's visible the construction of the listview when we arrive at the second page, and I want to avoid that, I want the list all build when we land in the #addresses page.
I also have a delay click in the listview in iPhone.
My code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>izigo.mobile</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(document).bind("mobileinit", function ()
{
$.mobile.toolbar.prototype.options.addBackBtn = true;
$.mobile.toolbar.prototype.options.backBtnText = "voltar";
$.mobile.page.prototype.options.domCache = true;
});
</script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script>
/* Pass data with changePage */
$(document).on("pageinit", "#homepage", function ()
{
$(".category").on("click", function ()
{
$.mobile.pageContainer.pagecontainer("change", "#addresses",
{
categoryId: this.id,
transition: "slide"
});
});
});
/* retrieve data and run function to add elements */
$(document).on("pagebeforechange", function (e, data)
{
if (data.toPage[0].id == "addresses")
{
var categoryId = data.options.categoryId;
clearListCategory("#addresses");
buildListCategory("#addresses", categoryId);
}
});
function clearListCategory(page)
{
var $page = $(page);
$("ul", $page).remove();
}
function buildListCategory(page, categoryId)
{
$.ajax({
type: "POST",
url: "http://10.0.0.200/api/Mobile/GetAddresses",
crossDomain: false,
beforeSend: function () { $.mobile.loading('show') },
complete: function () { $.mobile.loading('hide') },
data: { CategoryId: categoryId },
dataType: 'json',
success: function (addresses)
{
showAddresses(page, addresses);
},
error: function () {
console.log("loadList error!");
}
});
}
function showAddresses(page, addresses)
{
var $page = $(page);
var list = $("<ul/>", {
"data-role": "listview"
});
var items = '';
$.each(addresses, function (i, address)
{
items = $("<li>" + address.Name + "</li>");
list.append(items);
});
$(".ui-content", $page).append(list);
$("ul", $page).listview();
}
</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- home-page -->
<div data-role="page" id="homepage">
<div data-role="header" data-position="fixed"><h1>mobile</h1></div>
<div class="ui-content" role="main">
<ul data-role="listview" id="categories">
<li>Oficina</li>
<li>Seguro</li>
<li>Reboque</li>
</ul>
</div>
</div>
<!-- page addresses list -->
<div data-role="page" id="addresses">
<div data-role="header" data-position="fixed"><h1>mobile</h1></div>
<div class="ui-content" role="main"></div>
</div>
</body>
</html>
The code you're using, you populate listview on pagebeforechange event, which is triggered before any other page event. You should populate listview before you navigate to target page, using .success or .complete callback.
$.ajax({
type: "POST",
url: "URL",
crossDomain: false,
beforeSend: function () {
$.mobile.loading('show')
},
complete: function () {
$.mobile.loading('hide')
},
data: {
CategoryId: categoryId
},
dataType: 'json',
success: function (addresses) {
showAddresses(page, addresses);
$.mobile.pageContainer.pagecontainer("change", "#addresses");
},
error: function () {
console.log("loadList error!");
}
});
Demo - Code

jquery change function on dropdown value

I have a dropdown in my view to which i want to apply jquery(ajax onChange value). So that JSon data passed for the selected value by controller action rendered over the same view by replacing some id of that view
Dropdown
<div><select id="package_master" name="package_master"><option value="">
--select package--</option>
<option value="1">JPMC Package1</option>
<option value="2">JPMC Package 2</option>
<option value="3">JPMC Package1</option>
<option value="5">Select Package</option>
<option value="6">Select Package</option>
</select></div>
What i am presently doing is
<script type="text/javascript">
$(function () { //$(document).ready(function () {
$("#package_master").change(function () {
var value = $('#package_master').val();
jQuery.ajax({
type: "POST",
url: "#Url.Content("~/Test/getPackageDetails/")",
data: "packageID="+value,
success: function(data){//here i want to Replace come id with json data passed by action
</script>
url is url: "#Url.Content("~/Test/getPackageDetails/")",
Complete Above script
Updated:I used following script to accomplish my task which is working fine too, but data is displayed in array format like ["abc","xyz"]Now here i need help to format json data in row format i.e 1 row for each array element like abcxyz
`
<script type="text/javascript">
$(function () { //$(document).ready(function () {
$("#package_master").change(function () {
var value = $('#package_master').val();
jQuery.ajax({
type: "POST",
url: "#Url.Content("~/Test/getPackageDetails/")",
data: "packageID="+value,
success: function(data){
$("#packageDetails").html(JSON.stringify(data));
},
error: function(data){
alert("Request couldn't be processed. Please try again later. the reason "+data);
}
});
});
});
`
<script>
$(function () {
$("#package_master").change(function () {
var data = { packageID: $(this).val() }
$.post("url", data, function (backdata, status) {
// callback, do something
}, "json");
});
});
</script>
<script type="text/javascript">
$(function () { //$(document).ready(function () {
$("#package_master").change(function () {
var value = $('#package_master').val();
jQuery.ajax({
type: "POST",
url: "#Url.Content("~/Test/getPackageDetails/")",
data: "packageID="+value,
success: function(data){
data = $.map(data, function (item, a)
{
return " "+item+ "<br>";
});
$("#packageDetails").html(data.join(""));
},
error: function(data){
alert("Request couldn't be processed. Please try again later. the reason "+data);
}
});
});
});
jQuery ajax function has an option: dataType: "json"
Since you are using JSON.stringify(data) you need this parameter as dataType: "text"
So there's no need for JSON.stringify(data).
$(function () { $(document).ready(function () {
$("#package_master").change(function () {
var packageID = $('#package_master').val();
$.post("#Url.Content("~/Test/getPackageDetails/")", {packageID : packageID}, function (data) {
$("#packageDetails").html("");
$.each(data,function(i,field){
$("#packageDetails").append(i+1+" "+field+"<br/>");
});
}, "json");
});
});
Alternatively you can use
$("#packageDetails").$(selector).load(url,data,function(response,status,xhr))
for other solutions, see here. And I'd recommend to avoid using $.ajax if you have some alt.

How to return jquery autocomplete result to the separate div?

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'>

Resources