Skip to content

Instantly share code, notes, and snippets.

@awartoft
Created July 12, 2012 14:56
Show Gist options
  • Save awartoft/3098629 to your computer and use it in GitHub Desktop.
Save awartoft/3098629 to your computer and use it in GitHub Desktop.
(function($) {
$.widget('mcn.tagGeographicalArea', {
options: {
apiUrl: 'api/geographical-area/municipality/auto-complete'
},
tags: {
},
provinces: {},
_create: function() {
var el = this.element;
var o = this.options;
var self = this;
this.list = $('ul', el)[0];
this.input = $('input', el)[0];
this.dialogTemplate = $('<div><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Den kommunen är redan taggad.</p></div>');
// Apply some style
$(this.input).css({
marginBottom: '5px'
});
$(this.list).css({
marginBottom: '10px'
});
$.getJSON(
'api/geographical-area/fetch-all',
function(rawData)
{
var data = [];
// Save the rawData
this.provinces = rawData.provinces;
$.each(rawData.provinces, function(index, province) {
data.push({
id: province.id,
type: 'province',
value: 'Län: ' + province.name
});
$.each(province.municipalities, function(index, municipality) {
data.push({
id: municipality.id,
type: 'municipality',
value: 'Kommun: ' + municipality.name
})
});
});
$(self.input).autocomplete({
source: data,
select: function(evt, ui)
{
evt.preventDefault();
if (ui.item.type == 'province') {
$.each(this.provinces, function(index, province) {
if(province.id == ui.item.id) {
$.each(province.municipalities, function(index, municipality) {
this.add(municipality.id, municipality.name);
}.bind(this))
}
}.bind(this));
} else {
self.add(ui.item.id, ui.item.label.substring(8));
}
// Clear
evt.target.value = '';
}.bind(this)
});
}.bind(this)
);
},
add: function(id, label)
{
if (this.tags[id] != undefined) {
$(this.dialogTemplate).dialog({
modal: true,
draggable: false,
resizable: false,
height: 100
});
return;
}
var li = $('<li></li>');
var label = $('<span>' + label + '</span>');
var image = $('<img data-id="' + id + '" src="images/admin/icons/action_delete.png" style="float:left;" alt=""/>');
var input = $('<input type="hidden" name="article[geographical_areas[]]" value="' + id + '"/>');
// Append Stuff
$(label).appendTo(li);
$(image).appendTo(li);
$(input).appendTo(li);
// Handle delete event
$(image).click(function(evt) {
this.delete($(evt.target).data('id'));
}.bind(this));
// add the entire container to the list
this.tags[id] = li;
// Append li to the html list
li.appendTo(this.list);
},
delete: function(id)
{
// destroy the html code
$(this.tags[id]).remove();
// Remove it from the object
delete(this.tags[id]);
}
});
}) ( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment