jQuery Autocomplete id and item - autocomplete

I have a working query autocomplete code that completes the full_name when letters are typing. What I am trying to figure out is how to get the user_id for that goes with the full_name. I have JSON that comes back like so:
[{"full_name":"Matt","user_id":"2"},{"full_name":"Jack","user_id":"9"},{"full_name":"Ace","user_id":"10"},{"full_name":"tempaccount","user_id":"11"},{"full_name":"Garrett","user_id":"26"},{"full_name":"Joe","user_id":"29"},{"full_name":"Raptors","user_id":"32"}]
Below is my jQuery code. I am using PHPfox framework.
$(function(){
//attach autocomplete
$("#to").autocomplete({
//define callback to format results
source: function(req, add){
//pass request to server
//$.getJSON("friends.php?callback=?", req, function(data) {
$.ajaxCall('phpfoxsamplee.auto', 'startsWith='+req.term)
.done(function( data ) {
//create array for response objects
var suggestions = [];
var data = $.parseJSON(data);
//process response
$.each(data, function(i, val){
//suggestions.push(val.full_name,val.user_id); (This works and shows both the full name and id in the dropdown. I want the name to be visible and the ID to goto a hidden input field)
suggestions.push({
id: val.user_id,
name: val.full_name
});
});
//pass array to callback
add(suggestions);
});
},
//define select handler
select: function(e, ui) {
//create formatted friend
alert(ui.item.full_name); //Trying to view the full_name (doesn't work)
alert(ui.item.id); // trying to view the id (doesn't work)
var friend = ui.item.full_name, (doesn't work)
//var friend = ui.item.value, (This works if I do not try to push labels with values)
span = $("<span>").text(friend),
a = $("<a>").addClass("remove").attr({
href: "javascript:",
title: "Remove " + friend
}).text("x").appendTo(span);
//add friend to friend div
span.insertBefore("#to");
$("#to").attr("disabled",true);
$("#to").attr('name','test').attr('value', 'yes');
$("#to").hide();
},
//define select handler
change: function() {
//prevent 'to' field being updated and correct position
$("#to").val("").css("top", 2);
}
});
//add click handler to friends div
$("#friends").click(function(){
//focus 'to' field
$("#to").focus();
});
//add live handler for clicks on remove links
$(".remove", document.getElementById("friends")).live("click", function(){
//remove current friend
$(this).parent().remove();
$("#to").removeAttr("disabled");
$("#to").show();
//correct 'to' field position
if($("#friends span").length === 0) {
$("#to").css("top", 0);
}
});
});
HTML
<div id=friends class=ui-help-clearfix>
<input id='to' type=text name='player[" . $num . "][name]'></input>
</div>

Consider the JQuery Autocomplete Combobox. It is not a standard widget, but you can pretty much paste their source. And it will enable you to capture values corresponding to text selections.

Related

Ajax AutoComplete for jQuery "onEmpty"-type of event

I'm using Ajax Autocomplete for Jquery (https://www.devbridge.com/sourcery/components/jquery-autocomplete/) with DataTables to search on a specific column.
Using onSearchComplete and onSelect from Autocomplete I can filter both the input and the table together as the user is typing (onSearchComplete) and when they select an entry (onSelect):
$("#scoreboard_site_name_filter").autocomplete({
serviceUrl: "/wiki/extensions/CFBHA/models/_mSiteNames.php",
onSearchComplete: function(suggestion) {
update_scoreboard_by_site_name_filter(suggestion);
},
onSelect: function(suggestion) {
update_scoreboard_by_site_name_filter(suggestion);
}
});
function update_scoreboard_by_site_name_filter(suggestion) {
var colname = "site_name:name";
if (scoreboard.column(colname).search() !== suggestion) {
scoreboard.column(colname).search(suggestion).draw();
}
};
However, when the input is deleted, then the DataTable is left filtered on the last input because neither event is fired in that case.
I've tried the keyup and change events on the input itself to pass an empty string to the DataTable search:
$("#scoreboard_site_name_filter").on("keyup change", function() {
var suggestion = "";
update_scoreboard_by_site_name_filter(suggestion);
});
If I place it before the autocomplete then it has no affect and if I place it after then of course I lose the ability to filter the table as I type because it fires after the autocomplete.
How can I detect when the input has been deleted and then re-filter the table on an empty string (i.e., clear that filter)?
OK, I was overthinking it . . .
I removed the onSearchComplete event and just went with the input event on the input itself and everything is working great.
I left the onSelect for the Autocomplete and am now properly passing suggestion.value instead of suggestion.
Here's the proper code for anyone interested:
$("#scoreboard_site_name_filter").on("keyup change", function() {
update_scoreboard_by_site_name_filter(this.value);
});
$("#scoreboard_site_name_filter").autocomplete({
serviceUrl: "/wiki/extensions/CFBHA/models/_mSiteNames.php",
onSelect: function(suggestion) {
update_scoreboard_by_site_name_filter(suggestion.value);
}
});
function update_scoreboard_by_site_name_filter(suggestion) {
var colname = "site_name:name";
if (scoreboard.column(colname).search() !== suggestion) {
scoreboard.column(colname).search(suggestion).draw();
}
};
Additionally I updated the code to make the search regex if the suggestion is actually selected (clicked on or entered on) and to add a class to the input as an indicator that the table is now filtered on that exact search term:
$("#scoreboard_site_name_filter").on("input", function() {
update_scoreboard_by_site_name_filter(this.value, false);
});
$("#scoreboard_site_name_filter").autocomplete({
serviceUrl: "/wiki/extensions/CFBHA/models/_mSiteNames.php",
onSelect: function(suggestion) {
update_scoreboard_by_site_name_filter(suggestion.value, true);
}
});
function update_scoreboard_by_site_name_filter(suggestion, selected) {
var colname = "site_name:name";
if (!selected) {
scoreboard.column(colname).search(suggestion).draw();
$("#scoreboard_site_name_filter").removeClass("autocomplete-input-selected");
} else {
scoreboard.column(colname).search("^" + suggestion + "$", true, false).draw();
$("#scoreboard_site_name_filter").addClass("autocomplete-input-selected");
};
};

Store the user searchword in mysql

I working on a little snippet, a live search with MySQL.
Now i think it could be nice to store/save which searchword the user, did the search on.
Example:
User search on
My new book
Then i want to store that to my databse.
The problem is with my script right now, where i trig the ajax on keyup. Then it will store.
M My My N My Ne My New .... and so on..
and so on, how can i come around this and only store the hole line ..?
$(function() {
$("#searchword").keyup(function(){
var text = $(this).val();
if (text != ' ') {
$('#result').html(" ");
$.ajax({
type: 'post',
url: 'livesearch.php',
data: { 'search': text },
success: function(dataReturn) {
$('#result').html(dataReturn);
}
});
}
});
});
I've created a storeText(txt,time) function that will take your text as first param and time to wait before sending ajax as second param. You can change the second parameter as per your need. Add your ajax call in the function below my comment and you're good to go.
$(function() {
$("#searchword").keyup(function(){
var text = $(this).val();
if (text != ' ') {
//THIS IS WHERE YOU CAN MODIFY THE TIME
storeText(text,1000);
$('#result').html(" ");
$.ajax({
type: 'post',
url: 'livesearch.php',
data: { 'search': text },
success: function(dataReturn) {
$('#result').html(dataReturn);
}
});
}
});
});
var timer;
function storeText(txt,time){
clearTimeout(timer);
timer = setTimeout(function(){
//ADD YOUR SAVE QUERY AJAX HERE
},time);
}
Here's a JSFiddle to see it in action: https://jsfiddle.net/3n2L2v6g/
Try typing anything in the text box, it waits 1000ms before executing the code where your ajax would be.

Json parse from Facebook events

I have had some trouble with fetching json from a groups events on facebook and then put them in a tableview to be used in a Appcelerator mobile app.
The idea is to have this as a calendar to show events for a club in a simple way.
I want to show the name of the event. The picture for that event and the date for the event.
All in a tablerow.
I have gotten to the part where i can get the Name and date for the events with this code:
Ti.UI.backgroundColor = '#dddddd';
var access_token='AAACEdEose0cBAAICGa4tFTcZAqCOGm2w9qPYGZBwNtJ1oZAcwaMAP2DDHZCN58cvVBZCHZADZAZBTPC8tTnpfQ7uGKI5j3SbMYcRmWquZCdPzhwZDZD';
var url = "https://graph.facebook.com/64306617564/events?&access_token=" + access_token ;
var win = Ti.UI.createWindow();
var table = Ti.UI.createTableView();
var tableData = [];
var json, data, row, name, start_time, id;
var xhr = Ti.Network.createHTTPClient({
onload: function() {
// Ti.API.debug(this.responseText);
json = JSON.parse(this.responseText);
for (i = 0; i < json.data.length; i++) {
data = json.data[i];
row = Ti.UI.createTableViewRow({
height:'60dp'
});
var name = Ti.UI.createLabel({
text:data.name,
font:{
fontSize:'18dp',
fontWeight:'bold'
},
height:'auto',
left:'50dp',
top:'5dp',
color:'#000',
touchEnabled:true
});
var start_time = Ti.UI.createLabel({
text:'"' + data.start_time + '"',
font:{
fontSize:'13dp'
},
height:'auto',
left:'15dp',
bottom:'5dp',
color:'#000',
touchEnabled:true
});
row.add(name);
row.add(start_time);
tableData.push(row);
}
table.setData(tableData);
},
onerror: function(e) {
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
alert('There was an error retrieving the remote data. Try again.');
},
timeout:5000
});
xhr.open("GET", url);
xhr.send();
But when i want the specific event to open in a new window when clicked i just get the event that lies last on the screen when i put this in a browser:
https://graph.facebook.com/64306617564/events?&access_token=AAACEdEose0cBAOLAFWMKPmvgqEwap1ldnl7DeZBDKJC6YTZC4Goh6K5NHsvpOFmFQaGp1IekVsCxZCZCz3lwGpRcQG9ZBkcMrZAnLk4As8kgZDZD
And the access token expires REALLY fast. Any ideas how to make an access token that lasts longer?
Well, the code i am using to open the window is:
table.addEventListener('click',function(e) {
// Create the new window with the link from the post
var blogWindow = Ti.UI.createWindow({
title : data.name,
modal : true,
barColor: '#050505',
backgroundColor: '#050505'
});
var webView = Ti.UI.createWebView({url:'http://www.facebook.com/events/' + data.id});
blogWindow.add(webView);
// Create the close button to go in the left area of the navbar popup
var close = Titanium.UI.createButton({
title: 'Close',
style: Titanium.UI.iPhone.SystemButtonStyle.PLAIN
});
blogWindow.setLeftNavButton(close);
// Handle the close event
close.addEventListener('click',function() {
blogWindow.close();
});
blogWindow.open();
});
win.add(table);
win.open();
in my opinion that should open the event that is clicked on by parsing the ID from the row and putting it after the link.
Am i retarded or what is wrong?
It doesnt matter on which event i click it just open the last one all of the times.
And how can i get a thumbnail for the events?
Pls help........
When you click on table to get value from data which is not available.You can achieve it using you custom variable try to put this line of code at your row creation where you add your row in array i.e.row.data = data; and on table click event get that object using this alert(e.source.data); and check it. Best luck

Handle selected event in autocomplete textbox using bootstrap Typeahead?

I want to run JavaScript function just after user select a value using autocomplete textbox bootstrap Typeahead.
I'm searching for something like selected event.
$('.typeahead').on('typeahead:selected', function(evt, item) {
// do what you want with the item here
})
$('.typeahead').typeahead({
updater: function(item) {
// do what you want with the item here
return item;
}
})
For an explanation of the way typeahead works for what you want to do here, taking the following code example:
HTML input field:
<input type="text" id="my-input-field" value="" />
JavaScript code block:
$('#my-input-field').typeahead({
source: function (query, process) {
return $.get('json-page.json', { query: query }, function (data) {
return process(data.options);
});
},
updater: function(item) {
myOwnFunction(item);
var $fld = $('#my-input-field');
return item;
}
})
Explanation:
Your input field is set as a typeahead field with the first line: $('#my-input-field').typeahead(
When text is entered, it fires the source: option to fetch the JSON list and display it to the user.
If a user clicks an item (or selects it with the cursor keys and enter), it then runs the updater: option. Note that it hasn't yet updated the text field with the selected value.
You can grab the selected item using the item variable and do what you want with it, e.g. myOwnFunction(item).
I've included an example of creating a reference to the input field itself $fld, in case you want to do something with it. Note that you can't reference the field using $(this).
You must then include the line return item; within the updater: option so the input field is actually updated with the item variable.
first time i've posted an answer on here (plenty of times I've found an answer here though), so here's my contribution, hope it helps. You should be able to detect a change - try this:
function bob(result) {
alert('hi bob, you typed: '+ result);
}
$('#myTypeAhead').change(function(){
var result = $(this).val()
//call your function here
bob(result);
});
According to their documentation, the proper way of handling selected event is by using this event handler:
$('#selector').on('typeahead:select', function(evt, item) {
console.log(evt)
console.log(item)
// Your Code Here
})
What worked for me is below:
$('#someinput').typeahead({
source: ['test1', 'test2'],
afterSelect: function (item) {
// do what is needed with item
//and then, for example ,focus on some other control
$("#someelementID").focus();
}
});
I created an extension that includes that feature.
https://github.com/tcrosen/twitter-bootstrap-typeahead
source: function (query, process) {
return $.get(
url,
{ query: query },
function (data) {
limit: 10,
data = $.parseJSON(data);
return process(data);
}
);
},
afterSelect: function(item) {
$("#divId").val(item.id);
$("#divId").val(item.name);
}
Fully working example with some tricks. Assuming you are searching for trademarks and you want to get the selected trademark Id.
In your view MVC,
#Html.TextBoxFor(model => model.TrademarkName, new { id = "txtTrademarkName", #class = "form-control",
autocomplete = "off", dataprovide = "typeahead" })
#Html.HiddenFor(model => model.TrademarkId, new { id = "hdnTrademarkId" })
Html
<input type="text" id="txtTrademarkName" autocomplete="off" dataprovide="typeahead" class="form-control" value="" maxlength="100" />
<input type="hidden" id="hdnTrademarkId" />
In your JQuery,
$(document).ready(function () {
var trademarksHashMap = {};
var lastTrademarkNameChosen = "";
$("#txtTrademarkName").typeahead({
source: function (queryValue, process) {
// Although you receive queryValue,
// but the value is not accurate in case of cutting (Ctrl + X) the text from the text box.
// So, get the value from the input itself.
queryValue = $("#txtTrademarkName").val();
queryValue = queryValue.trim();// Trim to ignore spaces.
// If no text is entered, set the hidden value of TrademarkId to null and return.
if (queryValue.length === 0) {
$("#hdnTrademarkId").val(null);
return 0;
}
// If the entered text is the last chosen text, no need to search again.
if (lastTrademarkNameChosen === queryValue) {
return 0;
}
// Set the trademarkId to null as the entered text, doesn't match anything.
$("#hdnTrademarkId").val(null);
var url = "/areaname/controllername/SearchTrademarks";
var params = { trademarkName: queryValue };
// Your get method should return a limited set (for example: 10 records) that starts with {{queryValue}}.
// Return a list (of length 10) of object {id, text}.
return $.get(url, params, function (data) {
// Keeps the current displayed items in popup.
var trademarks = [];
// Loop through and push to the array.
$.each(data, function (i, item) {
var itemToDisplay = item.text;
trademarksHashMap[itemToDisplay] = item;
trademarks.push(itemToDisplay);
});
// Process the details and the popup will be shown with the limited set of data returned.
process(trademarks);
});
},
updater: function (itemToDisplay) {
// The user selectes a value using the mouse, now get the trademark id by the selected text.
var selectedTrademarkId = parseInt(trademarksHashMap[itemToDisplay].value);
$("#hdnTrademarkId").val(selectedTrademarkId);
// Save the last chosen text to prevent searching if the text not changed.
lastTrademarkNameChosen = itemToDisplay;
// return the text to be displayed inside the textbox.
return itemToDisplay;
}
});
});

getting class attr in jquery

I have some divs that are generated dynamically with content. I add the content id to the class for the div like so:
<div class="div-1"></div>
<div class="div-3"></div>
<div class="div-6"></div>
<div class="div-8"></div>
How do I select the id for a div because I need it as a param to send via ajax. e.g. I need to get the 1 when I click on the 1st div, 3 when I click on 2nd and so on
var id = $(this).attr('class').replace('div-', '');
Or even simple
var id = this.className.replace('div-', '');
Where this points to the dom element you click on inside the click handler.
//Here instead of document it is better to specify a parent container of all divs
$(document).on('click', '[class^="div-"]', function(){
var id = this.className.replace('div-', '');
});
Try this, and remember changing "div" for your selector:
$(document).on("click", "div", function() {
var class_elem = $(this).attr("class").split("-");
var n = class_elem[1]; // This is your number
});
The correct jQuery syntax is:
$("div").click( function() {
var id = $(this).attr('class').replace('div-', '');
});