MagicSuggest: redirect after choosing item - javascript

I am using MagicSuggest (http://nicolasbize.github.io/magicsuggest/) with CakePHP in a Helper as a contact search.
My MagicSuggestHelper class looks like the following:
class MagicSuggestHelper extends AppHelper {
var $name = 'MagicSuggest';
var $helpers = array('Html');
public function suggest(array $options=null){
?>
<div id='ms1'></div>
<script>
var ms = $('#ms1').magicSuggest({
width: 300,
highlight: true,
allowFreeEntries: false,
hideTrigger: true,
expandOnFocus: true,
useTabKey: true,
maxSelection: 1,
typeDelay: 0,
name: "searchId",
data: [
<?php foreach($options['data'] as $suggestions){
echo"{\n";
echo"id: ".$suggestions['id'].",\n";
echo"name: \"".$suggestions['name']."\",\n";
echo"desc: \"".$suggestions['desc']."\",\n";
echo"image: \"".$suggestions['image']."\",\n";
echo"},";
} ?>
],
renderer: function(v){
return '<div>' +
'<div style="float:left;"><img src="' + v.image + '"/ style=\"max-width:80px;max-height:80px\""></div>' +
'<div style="padding-left: 100px;">' +
'<div style="padding-top: 10px;font-style:bold;font-size:100%;color:#333">' + v.name + '</div>' +
'<div style="color: #999">' + v.desc + '</div>' +
'</div>' +
'</div><div style="clear:both;"></div>';
}
});
</script>
<?php
}
This works fine for me. But when selecting an item I want to get redirected directly to the profile I just clicked on.
I tried it with an onclick()-event in the first of the result which unfortunately didn't fired correctly when I used the CakePHP-HTML-Helper combined with $suggestions['id'].
On the MagicSuggest website I found an event that is fired when changing the selection The following code can be found in the FAQ:
$(ms).on('selectionchange', function(event, combo, selection){
alert(selection); });
I think I can use a redirect-Function here instead of the alert.
But how to get the id here? Even alert(selection) returns me an alert with "object Object" which I think should not be the case.
So how can I get the id here and redirect to my Contact view? (/contacts/view/$id).
I didn't worked alot with JavaScript in the past so please also excuse beginner's mistakes.
Thanks!

You can simply do this:
$(ms).on('selectionchange', function(e,m){
var val = this.getValue(); // this is what you want
});

Related

Using HTML inside jQuery code to pull part of a url and reuse it elsewhere?

The foundation: I have a simple lightbox on my home page (code below). It works exactly as I want it to: when the trigger image is clicked, it grays out the rest of the page and adds HTML to create an iframe for the text-based page that I want to display.
The problem: I need to create a lightbox where the content is dynamically chosen depending on the image that is clicked. The URLs will correspond to each other -- for example, if the user clicks "/media/X.png," he/she will be presented with a lightbox containing the iframe of the page "/X.html."
How can I accomplish this? My first stab at it is below (after the original, static lightbox code). It's cobbled together from various things I've read online and other answers to similar questions on StackOverflow, but I'm super new to jQuery / basically known no Javascript and I suspect I'm misusing variable assignment and the "split" function.
Many thanks.
EDIT: Someone has helped me insert the variable into the HTML (below). However, I think I'm assigning the variables incorrectly (see the beginning of the second block of code). Here's what I'm trying to do with each variable:
1. pre_lightbox_trigger: grab the string "X.png" from the image that the user has clicked.
2. lightbox_trigger: grab "X" only (remove ".png").
3. lightbox_trigger_href: make X into "X.html", and make it a link.
Code:
Original, static lightbox:
$(document).ready(function($) {
$('.lightbox_trigger').click(function(e) {
e.preventDefault();
if ($('#lightbox').length > 0) {
$('#lightbox').show();
}
else {
var lightbox =
'<div id="lightbox">' +
'<div id="content">' +
'<iframe src="why.html" id="lightframe" frameborder="0" seamless>' +
'</iframe>' +
'</div>' +
'<p>Click outside to close</p>' +
'</div>';
$('body').append(lightbox);
}
$(document).on('click', '#lightbox', function() {
$('#lightbox').hide();
});
});
});
My attempt to create a dynamic link:
$(document).ready(function($) {
$('.lightbox_trigger').click(function(e) {
e.preventDefault();
var pre_lightbox_trigger = location.'.lightbox_trigger'.split('/').pop();
var lightbox_trigger = pre_lightbox_trigger.split('.').pop(1);
var lightbox_trigger_href = lightbox_trigger + ".html";
if ($('#lightbox').length > 0) {
$('#lightbox').show();
}
else {
var lightbox =
'<div id="lightbox">' +
'<div id="content">' +
'<iframe src=$lightbox_trigger_href id="lightframe" frameborder="0" seamless>' +
'</iframe>' +
'</div>' +
'<p>Click outside to close</p>' +
'</div>';
$('body').append(lightbox);
}
$(document).on('click', '#lightbox', function() {
$('#lightbox').hide();
});
});
});
EDIT #2: Currently my "static" version of the lightbox is only for "trigger_small.png." However, I want a lightbox to appear when other images are clicked as well (for example, "vio_mass.png"). See below for sample HTML:
<div id="trigger">
<a class="lightbox_trigger" href="media/trigger_small.png">
<img src="media/trigger_small.png">
</a>
</div>
<div class="cat" id="violence_cat">
<div class="cat_grid" id="vio_1">
</div>
<div class="cat_grid" id="vio_2">
<img src="media/vio_mass.png">
</div>
...etc.
Instead of
var lightbox =
'<div id="lightbox">' +
'<div id="content">' +
'<iframe src=$lightbox_trigger_href id="lightframe" frameborder="0" seamless>' +
'</iframe>' +
'</div>' +
'<p>Click outside to close</p>' +
'</div>';
You would do
var lightbox =
'<div id="lightbox">' +
'<div id="content">' +
'<iframe src=' + lightbox_trigger_href + ' id="lightframe" frameborder="0" seamless>' +
'</iframe>' +
'</div>' +
'<p>Click outside to close</p>' +
'</div>';

ExtJS 4.2.1 - add textfield to an XTemplate

I got a custom component in which i set the html with an xtemplate something like this
Ext.apply(me, { html: mainTpl.apply() });
I want to add some textfields to my XTemplate too and i cant figure out how to do this.
new Ext.XTemplate('<div Class="TopHeaderUserInfo"><div id="TopHeaderLanguageDiv" ><div Class="ActiveLanguageFlag" lang="{[ this.getLanguage() ]}" ></div>' +
'<ul Class="LangSelectDropDown HeaderDropDown" style="position:absolute;"><li class="ListHeader">' + MR.locale.SelectLanguage + '</li>{[ this.renderLanguageItems() ]}</ul>' +
'</div>{[this.renderUserInfo()]}</div>',
{
...
...
...
renderUserInfo: function () {
return (MR.classes.CurrentUser.user == null ?
'<div Class="LogInOut" Id="TopHeaderLoginLogoutLink"><a Class="Login">' + MR.locale['Login'] :
'<span>Welcome, ' + MR.classes.CurrentUser.getUser().get('FullName') + '</span> <a Class="Logout">' + MR.locale['Logout']) + '</a>' +
'<ul Class="HeaderDropDown LoginDropDown" style="position:absolute;"><li class="ListHeader">Header</li>' +
// INSERT TEXTFIELD HERE
'</ul>' +
'</div>';
}
})
please help - i dont know how to continue. couldnt find a solution in the web.
If you need any further information, dont hesitate to ask!
Here is a workaround. Tested with ExtJS 4.2.2.
You have to add to the template some container with an ID or a class name (e.g. <li class="custom-text-field"></li>). Then add handler for render event of your custom component. The handler will automatically insert your text field right after the template is rendered.
Ext.define('MyComponent', {
extend: 'Ext.container.Container',
initComponent: function() {
var me = this,
// just create a textfield and do not add it to any component
text = Ext.create('Ext.form.field.Text');
var mainTpl = new Ext.XTemplate("<div>{[this.renderUserInfo()]}</div>", {
renderUserInfo: function() {
return '<ul>' +
'<li class="custom-text-field"></li>' +
'</ul>';
}
}
);
me.html = mainTpl.apply();
// postpone text field rendering
me.on('render', function() {
// render text field to the <li class=".custom-text-field"></li>
text.render(me.getEl().down('.custom-text-field'));
});
this.callParent();
}
});
Ext.getBody().setHTML('');
Ext.create('MyComponent', {
renderTo: Ext.getBody()
});

Create HTML table in Javascript with JSON or jQuery

I'm not any good at JavaScript (yet!) - I really need some help to get past this stuck point that is causing me lots of premature hair loss!
I just can't seem to figure out how to build the following HTML code using JSON data.
This is a sample of the JSON data that I have being generated for the new version of this page I'm working on:
[{"id":"1732","name":"1BR House","checkin":"2012-12-20","checkout":"2012-12-23","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1587","name":1BR House","checkin":"2012-12-23","checkout":"2013-01-01","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1661","name":"2BR Studio","checkin":"2012-12-25","checkout":"2013-01-02","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1829","name":"Studio Cottage","checkin":"2012-12-25","checkout":"2012-12-29","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1787","name":"Studio Cottage","checkin":"2012-12-29","checkout":"2013-01-08","inclean_cleaner":"","inclean_datetime":"2012-12-29 00:00:00","inclean_notes":""},{"id":"1843","name":"1BR House","checkin":"2013-01-07","checkout":"2013-01-19","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1970","name":"Studio Cottage","checkin":"2013-01-12","checkout":"2013-01-19","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1942","name":"Suite","checkin":"2013-01-15","checkout":"2013-01-20","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""}]
To illustrate the HTML result I need, here is how I currently do it without JSON (strictly in PHP):
<div class="'.$dashboard_list_line_class.'">
<div class="dashboard_list_unitname"> '.$unit_name.'</div>
<div class="dashboard_list_cleaner_datetime"> '.$inclean_datetime.'</div>
<div class="dashboard_list_cleaner_checkin"> '.$checkin.'</div>
<div class="dashboard_list_cleaner_checkout"> '.$checkout.'</div>
<div class="dashboard_list_cleaner_inclean_cleaner"> '.$inclean_cleaner.'</div>
<div class="dashboard_list_cleaner_notes"> '.$inclean_notes.'</div>
</div>
What would the code look like in jQuery or JavaScript to grab the JSON, iterate though the arrays and create the same result as the PHP I have shown? I've been trying for hours, and get different results of puling data - but I just can't make it work.
Thanks for your help!
Here is you complete solution:
$.ajax( "example.php" ).done(function (response) {
//var data = [{"id":"1732","name":"1BR House","checkin":"2012-12-20","checkout":"2012-12-23","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1587","name":"1BR House","checkin":"2012-12-23","checkout":"2013-01-01","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1661","name":"2BR Studio","checkin":"2012-12-25","checkout":"2013-01-02","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1829","name":"Studio Cottage","checkin":"2012-12-25","checkout":"2012-12-29","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1787","name":"Studio Cottage","checkin":"2012-12-29","checkout":"2013-01-08","inclean_cleaner":"","inclean_datetime":"2012-12-29 00:00:00","inclean_notes":""},{"id":"1843","name":"1BR House","checkin":"2013-01-07","checkout":"2013-01-19","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1970","name":"Studio Cottage","checkin":"2013-01-12","checkout":"2013-01-19","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1942","name":"Suite","checkin":"2013-01-15","checkout":"2013-01-20","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""}];
var data = $.parseJSON(response);
var dashboard_list_unitname = 'change_this';
var booking_id = 'also_change_this';
$(data).each(function (i, row) {
$(row).each(function (j, col) {
var html = '<div class="row_' + i + '">' +
'<div class="' + dashboard_list_unitname + '"> ' + col.name + '</div>' +
'<div class="dashboard_list_cleaner_datetime"> ' + col.inclean_datetime + '</div>' +
'<div class="dashboard_list_cleaner_checkin"> ' + col.checkin + '</div>' +
'<div class="dashboard_list_cleaner_checkout"> ' + col.checkout + '</div>' +
'<div class="dashboard_list_cleaner_inclean_cleaner"> ' + col.inclean_cleaner + '</div>' +
'<div class="dashboard_list_cleaner_notes"> ' + col.inclean_notes + '</div>' +
'</div>';
$('body').append($(html));
});
});
});
jQuery templates can help here.
http://api.jquery.com/jquery.tmpl/ shows several examples of a template being populated from a JSON-like data bundle, and the {{each}} element allows you to iterate over lists to populate rows and cells.
Template:
<li>
Title: ${Name}.
{{each Languages}}
${$index + 1}: <em>${$value}. </em>
{{/each}}
</li>
Data:
var movies = [
{ Name: "Meet Joe Black", Languages: ["French"] },
{ Name: "The Mighty", Languages: [] },
{ Name: "City Hunter", Languages: ["Mandarin", "Cantonese"] }
];
Everyone seems to be assuming knowledge of AJAX calls. It's not complicated, here is an example,
$.get('json/url', function(json_data) {
// do stuff with your data
// like, other people suggested json_data.each(function(item) {
// do stuff
// });
});
You can learn more about it straight from the jQuery docs,
http://api.jquery.com/jQuery.get/
If you need to make a post request just consult the jQuery docs for post, or for the more general article, the jQuery docs for AJAX calls: http://api.jquery.com/jQuery.ajax/.
var table = '';
$.each(json_data, function(index, obj) {
table += '<div>';
for(var x in obj) {
table += '<div class="dashboard_list_unitname"> '+ obj[x]+'</div>';
}
table += '</div>';
});

Getting store record of list item when selecting a pic within the list

So I havea list of posts in a forum format, and right now I want to be able to access the posterID property of the store post when clicking on the avatar image of the user. I've attached a select listener to the image, but I'm unsure how to access the parent store of the image. I've tried looking through sencha's documentation and search has failed me.
store: 'topicStore',
itemTpl:
'<div class="post">' +
'<div class="header">' +
'<img id="avatar" src="{avatar}" width=48 height=48>' +
'<h2>{displayName}</h2>' +
'<div class="date">on {postDate:date("m/d/Y")}</div>' +
'</div>' +
'<div class="body">' +
'{message}' +
'</div>' +
'<tpl if="signature">' +
'<hr />' +
'<div class="signature">' +
'{signature}' +
'</div>' +
'</tpl>' +
'</div>',
listeners: {
select: function() { return false;},
tap: {
fn: function(event, el, record){
tempElement = el.src;
if (el.id != 'avatar'){
tempElement = tempElement.replace('_th.jpg', '_mid.jpg');
var logo = Ext.create( 'Ext.Img', {
src: tempElement,
id: 'logo',
mode: 'element'
});
app.fireEvent('forum-onimgview',logo);
}
else if (el.id == 'avatar'){
console.log(record);
}
},
element: 'element',
delegate: 'img'
}
}
Does anyone know how to get the parent store of the selected Item? All the gets returned on the listener is the image and dom elements. Thanks in advance!
Try using itemTap listener, it will give you reference to the list.
I use it like this:
listeners: {
itemtap: function (list, index, element, record)
{
/* Put your logic here*/
}
}
More details can be found here: http://docs.sencha.com/touch/2-1/#!/api/Ext.dataview.DataView-event-itemtap

How to redirect to another page with jQuery Autocomplete item click

I'm stumped with this one, I've been at it hours, trying to get jQuery autocomplete to go to another page on the site when an item is clicked in the suggestions list.
Anyone know how to do this? Here is my code :
$(':input[data-autocomplete]').autocomplete({
source: $(':input[data-autocomplete]').attr("data-autocomplete"),
delay: 0,
select: function (event, item) {
//window.location.replace("http://www.example.com/Profile/Details/1");// Works but totally unacceptable, browser history lost etc..
//alert("Item Clicked"); //Fires Ok
}
}).data("autocomplete")._renderItem = function (ul, item) {
var MyHtml = '<a id="ItemUrl" href="/Profile/Details/' + item.PartyId + '"' + ">" +
"<div class='ac' >" +
"<div class='ac_img_wrap' >" +
'<img src="../../uploads/' + item.imageUrl + '.jpg"' + 'width="40" height="40" />' +
"</div>" +
"<div class='ac_mid' >" +
"<div class='ac_name' >" + item.value + "</div>" +
"<div class='ac_info' >" + item.info + " PartyId :" + item.PartyId + "</div>" +
"</div>" +
"</div>" +
"</a>";
return $("<li></li>").data("item.autocomplete", item).append(MyHtml).appendTo(ul);
};
As you can see I have used custom HTML in the _renderItem event, my custom HTML creates an anchor tag with the id passed in from the source, this looks ok, the link is formed correctly in the browser bottom left corner (I'm using Chrome)
<a href='/Profile/Details/id' >some other divs & stuff</a>
The problem is that when I click the link nothing happens, I have tried using the select event but item is null so can't get item.PartyId to force a manual jump.
How can I get the click event working?
It might late to answer it, but I have done this with the following code:
$(document).ready(function() {
$('#txtSearch').autocomplete({
minLength: 3,
source: "handlers/SearchAutoComplete.ashx?loc=" + $('#hfLocation').val(),
select: function(event, ui) {
doSearch(ui.item.label, ui.item.city);
}
});
});
function doSearch(term, location) {
window.location.href = 'Search.aspx?q=' + term + '&loc=' + location;
}
After a few days of head banging (not moshing kind) I've come up with the following:
$(':input[data-autocomplete]').autocomplete({
source: $(':input[data-autocomplete]').attr("data-autocomplete"),
delay: 0,
select: function (event, ui) {
var q = ui.item.PartyId;
if (q != "") {
$('#hidPID').val(q);
$('#ac_submit').trigger('click');
}
}).data("autocomplete")._renderItem // -->>> the rest of the code same as above
The issue was (event, item) should have been (event, ui) and to get the value of the item you use ui.item.PartyId (in my case PartyId is declared in the source : above)
So on my original form I had two html inputs 1-hidden ID, 2-Submit & as you can see in the select : function above I set the ID & trigger the submit (so now the user just picks an item and off they go to the controller which performs the RedirectToView & NOT this code as it doesn't seem correct to use location in this instance)
I Hope this saves someone some time as the jQuery autocomplete docs dont make it too clear.

Categories

Resources