How to use jQuery's formatItem, formatMatch, and formatResult options for .autocomplete? - jquery-plugins

I am making use of jQuery's .autocomplete plugin, and I would appreciate some assistance formating the results that show up in the dropdown menu that populates when text is written into the input field.
In order to get the data to populate the autocomplete, I pull from mySQL using this PHP:
$sql = ( 'SELECT tag, title, author, content, id FROM labels' );
$result = mysql_query( $sql );
$Response = array();
while( $row = mysql_fetch_object( $result ) ){
$Response[] = array(
"id" => $row->id,
"name" => $row->tag . ": " . $row->title . ": " . $row->content .""
);
}
When a user selects the option from the autocomplete that is best for them, I convert the "name" above into the "id" using this method:
var AllTagData = ;
var Tags = [];
for(var i in AllTagData){
Tags.push(AllTagData[i].name);
}
function getIdFromTag(_name){
for(var i in AllTagData){
if(_name == AllTagData[i].name){
return AllTagData[i].id;
}
}
}
So far, so good. Finally, I use the jQuery autocomplete plugin to output the data for the user:
$(document).ready(function(){
$("#Responses").autocomplete({
source: Tags,
matchContains: true,
autoFill: true,
select: function(e, ui){
$("#hidden_tags").val( getIdFromTags($("#Responses").val()) );
}});
});
This final portion of the code is where I need help implementing the formatItem, formatMatch, and formatResult options.
From the PHP given above, I output Tags, Title, and Content all in the "name". The way that I would like to format my autocomplete options for the user is
Show Tags & Title
Hide Content
Search through Tags, Title, and Content for possible matches
Therefore, even though I want the autocomplete to search through Content, I don't want Content showing up in the populated autocomplete list. I only want the Tags and Title to show.
I've been having a lot of trouble with this and have searched quite extensively to find an answer and would really appreciate any help you can give on how to accomplish this. Please ask any follow up questions if you need further clarification.
Thanks!

I think you are using a different version of the plugin, but if you look at this one:
http://code.google.com/p/jquery-autocomplete/
You will find a file index.html with the examples you ask for, for example:
showResult: function(value, data) {
return '<span style="color:red">' + value + '</span>';
},
Good luck!

Related

Autofill state and postcode according to the city in magento checkout page

Hi guys i have searched for it a lot but didn't find a good solution of it. I want to auto fill the postcode and state of Australia after customer enters their city in magento checkout page.What would be the best way to achieve this?Can you recommend some extensions if there is any or suggest some solutions. I tried to use the extension of Fontis but it didn't work.
So guys can someone help.Any help would be appreciated.
If you don't want to get into more complexity of code, here is a solution for you.
First Step:
download latest country zip code Excel file and locate that excel file under root folder.
Second Step:
Call ajax function in the last part of billing.phtml (../template/persistent/checkout/onepage/)
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type=”text/javascript”><br>
jQuery(document).ready(function(){
jQuery(‘.postcode‘).blur(function(){ //.postcode class of zipcode text field
var s = jQuery(this).val();
jQuery.ajax({
type: ‘POST’,
url:“http://www.sample.com/postcode.php“, //file which read zip code excel file
dataType: “json”, //is used for return multiple values
data: { ‘s’ : s },
success: function(data){
try {
jQuery(“.state“).val(data.state); //region-class of state text field
jQuery(“.city“).val(data.dist);//city-class of city text filed
} catch (e) {
alert(e.Message);
}
},
error:function (xhr, status, err){
alert( “status=” + xhr.responseText + “, error=” + err );
}
});
});
});
</script>
This Ajax function will call “http://www.sample.com/postcode.php” file
Under postcode.php file we have to read excel file and return state and city value
postcode.php
<?php
extract ($_POST);
$s=$_POST[‘s’]; //get value from ajax
$filename=”zip.csv“; //zipcode csv file(must reside in same folder)
$f = fopen($filename, “r”);
while ($row = fgetcsv($f))
{
if ($row[1] == $s) //1 mean number of column of zipcode
{
$district=$row[3]; //3- Number of city column
$state=$row[4]; //4-Number of state column
break;
}
}
fclose($f);
echo json_encode(
array(“dist” => $district,
“state” => $state,
“zip” => $s)
); //Pass those details by json
?>
That’s All, Enjoy
I got the solution of my question.As there is no answer provided i thought my answer may be helpful.At first my main problem is to create a table with the Australian postcodes, suburb and state. For that i googled a lot and after all i got the csv file of all these information. I filtered it according to my requirement.
Here is the link to the csv file that consist of Australian postcodes, suburb and state. here.
Now you can use this csv to create a table in a database which further is used in autocomplete.
All the codes that i have used may not be usable in your case so i didn't care to put it.
But i think this will help a lot.

Wordpress, wp-fullcalendar (0.8.4) with events manager (5.5.2): how to add additional text to title?

i'm in the nth hour of trying the following: i'd like to add text/html snippets before the title of an event as displayed in the fullcalendar (i.e. inside of <div class="fc-event-title">). These snippets would be one of the following:
<span class="info">registration needed</span>
<span class="cancelled">course cancelled</span>
<span class="ok">held as planned</span>
blank value/no additional text
I tried to copy wp-fullcalendar.php into my theme's directory hoping to be able to edit the function but couldn't accomplish to overwrite the original file - anyplace i tried to put it.
I then tried working in the source file, for a test i did (line 199 in original wp-fullcalendar.php):
$title = 'LLL' . $post->post_title; which did nothing to the output in the calendar.
After a while i completely removed the function 'function ajax()' from wp-fullcalendar.php and the calendar still displays just fine. Seems to be the wrong place (which it is anyway as it's a source file, i know).
I was hoping to find a quick way to accomplish my task but as you can see i'm stuck.
Any help on the matter would be highly appreciated. Thank you,
Frank
Update:
i added a custom attribute 'Kurstyp' to each Event.
possible values for it are: empty string (ie no extra span), 'please register', 'event cancelled', 'held as planned'
i would like all non empty values to appear within <div class="fc-event-title">
best each wrapped in a span with an individual class for styling purposes
this is what i added to wp-fullcalendar.php:
add_action('wp_ajax_wpfc_custominfo',array('WP_FullCalendar','custominfo') );
add_action('wp_ajax_nopriv_wpfc_custominfo', array('WP_FullCalendar','custominfo') );
// and further down
function custominfo() {
if( !empty($_REQUEST['post_id']) ){
$return = get_post_meta($_REQUEST['post_id'], 'Kurstyp', true);
}
echo apply_filters('wpfc_custominfo', $return);
die();
}
// then, inside the event.render part within fullcalendar_args
if(event.post_id > 0) {
alert('event.title (1st): ' + event.title);
var custominfo = {action: 'wpfc_custominfo', post_id: event.post_id};
var extra = $.ajax({
url: WPFC.ajaxurl,
type: "POST",
data: custominfo
});
extra.done(function(addtxt) {
event.title = addtxt + event.title;
alert('event.title (2nd): ' + event.title);
});
}
alert('event.title (3rd): ' + event.title);
addtxt delivers the correct value but my 3rd alert fires before the 2nd one, so event.title remains unchanged
all of this takes place in the original source, i'd want to change this even if it worked
also, even if it worked: how to style the different messages accordingly?
might the attribute className of the Event Object be helpful and if so, how?
The Texts used would be german, tried to use english here for better reading.
Thanks for your help, Frank

Coverting AJAX JSON function to return data objects instead of html into a modal window

Background
Okay, I have a page which displays simple information on rows from a mysql database. For example, the table has 7 columns, but only #'s 1, 3 & 4 are displayed on the page. On the right side of the row is a href link to open a modal window, and I am attempting to display all the rows, in a nicely formatted window with html/css/etc...
After spending about 4 hours in tutorials on this, the closest thing I have come up with is the code base below, which does the job of passing the "id" to the json script, (almost) properly pulls the information, puts it in a single object line, and passes it back into my html/php page to be read into the modal window.
I am politely asking for help to convert my codebase so that it transfers all objects individually instead of one gigantic line of php to echo into html (arse-backwards).
I am rather new to JSON/AJAX/jquery, but can navigate and work with the html/css/php once I am able to figure this out.
My apologies if the code examples are a little muffled and poor in syntax, I have spent hours trying to get this work as it is supposed to.
PHP Page With The AJAX
$('.view_information').click(function(e) { // Button which will activate our modal
//On Clicking the function, dynamically load the data for the viewing
var data_id = $(this).data('id');
$.ajax({
url: 'view_agency_info.php',
type: 'POST',
data: {id: data_id},
dataType: 'json',
success: function(data){
$('.view_modal_content').html(data.html); // LOAD THE DATA INTO THIS DIV
//I want to be able to use...
//$('.placeholder_name')xxxx
//$('.placeholder_accountnumber')etc
},
error: function(jqXHR, textStatus, errorThrown){
$('.view_modal_content').html('');
alert('Error Loading Information');
}
});
As you can see from the php page, as of right now, the mysql is being pulled into an array, then inserted individually into a single HTML object, then being passed back into PHP to be outputted. How can I convert this code to output more than just one object?
JSON
<?php
$customer_id=$_SESSION['customer']['customer_id'];
$id = (int)$_POST['id'];
$query = "SELECT * FROM collections_list WHERE id={$id} && customer_id=$customer_id LIMIT 1"; //expecting one row
$result = mysql_query( $query );
//$message = mysql_fetch_assoc( $result ); //expecting just one row
$message=array();
while ($row = mysql_fetch_assoc($result)) {
$message[]=$row['agency_name'];
$message[]=$row['account_number'];
$message[]=$row['phone'];
}
$json = array();
$json['html'] = '<p><pre><code>id:'.$id.'.<br>Agency Name: '.$message[0].'<br>Account Number:'.$message[1]."<br>Phone:".$message[2].'</code></pre></p>'.'<br><br>test';
header('Content-Type: application/json');
echo json_encode( $json );
?>
If I understand this correctly, then I would advise you to change the PHP to generate JSON directly rather than sending back HTML. Something like:
$first = 1;
$json = '[';
while ($row = mysql_fetch_assoc($result)) {
if ($first == 1) $first = 0; else $json = $json + ',';
$json = $json.'{';
$json = $json.'"AgencyName":'.$row['agency_name'];
$json = $json.', "AccountNumber":'.$row[account_number];
$json = $json.', "Phone":'.$row[phone];
$json = $json.'}';
}
$json = $json.']';
I have done this more in MVC and am rusty on PHP syntax, but hopefully this gets the gist across. Then your javascript can parse the results as just JSON. If you have "bad" characters in your data, you may have to html encode some, but the data should be easier to work with as data. You will have to provide template HTML for your modal and then fill it in.
The line:
$json['html'] = '<p><pre><code>id:'.$id.'.<br>Agency Name: '.$message[0].'<br>Account Number:'.$message[1]."<br>Phone:".$message[2].'</code></pre></p>'.'<br><br>test';
only pulls one object from the result "$message[0]" the first elememt of the array.
This is why you are only getting one object returned.
edit:
you'll need to change:
$message=array();
while ($row = mysql_fetch_assoc($result)) {
$message[]= ('name' => $row['agency_name'],
'account' => $row['account_number'],
'phone' => $message[]=$row['phone']
);
}
print json_encode($message);
This will then return a json object that you can parse with js
then in your js:
edit:
then add your html in js if thats how you wanna do it
var html;
$.each(data, function(info) {
html += "<p><pre><code>id:"+ data_id +".<br>Agency Name: "+ info.name +"<br>Account Number:"+ info.number +"<br>Phone:"+ info.phone +"</code></pre></p><br><br>";
});
$('.view_modal_content').html(html);
??????????????????????????????????????????????????????????????????
are you trying to do:
var divObj = {}; //make sure this is in the correct scope
//anonymous array
$.each(data, function(info) {
divObj.push("<p><pre><code>id:"+ data_id +".<br>Agency Name: "+ info.name +"<br>Account Number:"+ info.number +"<br>Phone:"+ info.phone +"</code></pre></p><br><br>");
});
//or associative array
$.each(data, function(info) {
divObj[info.name] ="<p><pre><code>id:"+ data_id +".<br>Agency Name: "+ info.name +"<br>Account Number:"+ info.number +"<br>Phone:"+ info.phone +"</code></pre></p><br><br>";
});
or are you trying to simply update elements of an existing block of code in a div?

How to add a custom validation to Magento prototype

I want to make a simple url validator for some custom fields. I tried the default ones (adding the class validate-url or validate-clean-url to the input) - but these don't work quite as I would like them to, so I want to write some of my own javascript, but integrated with the prototype validation.
Does anyone have any ideas how I can do this?
I didn't find anything helpful in my searches, and I am not very Prototype-savy (worked mostly with jQuery).
You can create your own custom validation function using
<script type="text/javascript">
var theForm = new VarienForm('theForm', true);
Validation.add('validate-must-be-baz','You failed to enter baz!',function(the_field_value){
if(the_field_value == 'baz')
{
return true;
}
return false;
});
</script>
See http://magento-quickies.tumblr.com/post/6579512188/magento-custom-form-validation
or
if(Validation) {
Validation.addAllThese([
[
'validation-myown',
'Please insert proper word',
function(v,r){ return v.indexOf('valid')==-1?false:true }
],
[ ]
])
}
see http://blog.baobaz.com/en/blog/custom-javascript-form-validators
In /js/prototype/validation.js (or the files for this kind of thing you have). You have a section with an array of :
classname :message on fail : function(v){your check return true/false;} to check if v is valid or not
This section is around line 420.
You can add your validation to this array or modify validate-url here is what it looks like :
['validate-url', 'Please enter a valid URL. Protocol is required (http://, https:// or ftp://)', function (v) {
v = (v || '').replace(/^\s+/, '').replace(/\s+$/, '');
return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9]([A-Z0-9_-]*[A-Z0-9]|))(\.[A-Z0-9]([A-Z0-9_-]*[A-Z0-9]|))*)(:(\d+))?(\/[A-Z0-9~](([A-Z0-9_~-]|\.)*[A-Z0-9~]|))*\/?(.*)?$/i.test(v)
}],
Edit : R.S answered maybe better by showing how to do without changing the js file. More convenient ;)

How to get values of jQuery Tags Input plugin

I use this jQuery Tags Input plugin:
jQuery Tags Input
but I can't get the values on my php file.
If you are trying to get the individual values using jQuery you can use:
(This is assuming the text input you made into a tag input has an id of "keywords")
$('#keywords').tagsInput({
'height':'auto',
'width':'350px',
'defaultText':'',
'delimiter': '|'
});
/*The delimiter option above overrides the default comma delimiter in the plugin allowing commas in tags if you prefer that...*/
var $keywords = $("#keywords").siblings(".tagsinput").children(".tag");
var tags = [];
for (var i = $keywords.length; i--;) {
tags.push($($keywords[i]).text().substring(0, $($keywords[i]).text().length - 1).trim());
}
/*Then if you only want the unique tags entered:*/
var uniqueTags = $.unique(tags);
alert(uniqueTags.toSource());
To get the list of emails from:
<input type="text" name="to_addresses" class="to_addresses" data-role="tagsinput" >
I use:
$emails = []
$.map($(".tagsinput span span"),function(e,i){
$emails.push($(e).text().trim());
})
Works for me, thought I'd share it.
$("#btn").click(function () {
var $tagWord = $("#tags_2").siblings(".tagsinput").children(".tag");
var tags = [];
for (var i = $tagWord.length; i--; ) {
tags.push($($tagWord[i]).text().substring(0, $($tagWord[i]).text().length - 1).trim());
}
/*Then if you only want the unique tags entered:*/
var uqTags = $.unique(tags);
alert(uqTags.toSource());
});
using jquery you can do it in one line:
$.map($('.tag span'),function(e,i){return $(e).text().trim();})
$("input").tagsinput('items')
["Amsterdam","Washington","Sydney","Beijing","Cairo"]
$("input").val()
"Amsterdam,Washington,Sydney,Beijing,Cairo"
can you provide an example of what is POSTed? you can do so by pointing your form to go to api.fatherstorm.com?query and copying the json data that it gives you
it change the hidden input value, and will post the data when you click submit , you can test it by a simple php script. print_r($_POST) to see it.
Based on sagivo answer you can write a function like this :
function getKeywords() {
return $.map($('.tag span'),function(e,i){
return $(e).text().trim();
});
}
That will return an array of keywords present in the input.
Like this [ "there", "it", "is" ]

Resources