Render json in ruby rails for jquery autocomplete - ruby-on-rails

This is my code which render json in format {"11":"xyz","14":"abc"}
def index
if params[:term] != nil
#products = Hash[current_user.search(params[:term]).map{|product| [product.id,product.name]}]
render json: #products.to_json
end
end
This is the javascript where I am updating div #results with autocomplete result. What I want is to make xyz and abc link with the ids associated with it but I am not able to figure out why I am losing ids all I am getting in results as xyz and abc`.
$(document).ready(function(){
$("#search").autocomplete({
//source: $('#search').data('autocomplete-source'),
source: "entities#index",
open: function(e, ui) {
var list = '';
var results = $('ul.ui-autocomplete.ui-widget-content a');
var ent_id = results.html()
results.each(function() {
list += '<a href= '+$(this).html()+'/'+ent_id+ '>' +$(this).html()+'</a>'+ '<br />';
});
$('#results').html(list);
}
})
} )
Right now above javascript code is not working as required because i am not able to get ids.
Thanks

I found a soulution for it.
$(document).ready(function(){
$( "#search" ).autocomplete(
{
source:"entities#index",
select: function( event, ui ) {
$( "#search" ).val( ui.item[1] );
$( "#results").empty();
$( "#results" ).append( '<a href= '+"entities"+'/'+ui.item[0]+ '>' +ui.item[1]+'</a>' );
return false;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item[1] + "</a>" )
.appendTo( ul );
};
} )

Related

Lack of selecting capacity with if statement / append method

I want to propose an autocomplete list (jquery ui 1.8) with some words in bold font.
The JSON source looks like :
{"especes":[{"fk_sp":number,"nom_espece":name,"nom_valide":0 or 1}].
My script is like that :
$(function(){
$('#id').autocomplete({
source: function(request, response) {
$.getJSON("fichier.php", {
term: request.term
}, function(data) {
var array = data.error ? [] : $.map(data.especes, function(m) {
return {
label: m.nom_espece,
value: m.fk_sp,
valid: m.nom_valide
};
});
response(array);
});
},
select: function (event, ui) {
$("#espece").val(ui.item.label);
$("#fk_sp").val(ui.item.value);
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( item.valid == '1' ? "<b>" + item.label + "</b>" : item.label)
.appendTo( ul );
};
});
If I use :
.data( "ui-autocomplete" ) => I have the good selectable list without the bold lines,
.data( "ui-Autocomplete" ) ou .data( "uiAutocomplete" ) => nothing works,
and if I juste write ._renderItem without .data( "ui-autocomplete" ) => I have a pretty list with the good names in bold, but I can't select any name of the list !
I don't find where is my error (I suppose it is somwhere with the "select :" part).

jQueryUI Autocomplete function not properly working on IE9

I am using this snippet of code for my jQueryUI Autocomplete function on my site,
$( "#find" ).autocomplete({
minLength: 1,
source: function(request, response) {
var results = $.ui.autocomplete.filter(locations, request.term);
response(results.slice(0, 10));
},
focus: function( event, ui ) {
$( "#find" ).val( ui.item.value );
return false;
},
appendTo: "#results",
open: function(){
var position = $("#results").position(),
left = position.left, top = position.top;
$("#results > ul").css({left: (left + 15) + "px",
top: (top + 30) + "px", width: (206) + "px" });
},
select: function( event, ui ) {
$( "#find" ).val( ui.item.value );
$(":header.title").html(ui.item.value);
var new_url = ui.item.href; // instead of adding 'statistics', by using location.hash, it wont be necessary unlike using pushState()
location.hash = new_url;
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br />" + item.desc + "</a>" )
.appendTo( ul );
};
Actually this works perfectly fine on Firefox and Chrome, it behaves just like what it exactly behaves on the sample given here, I just merely copied and modified it according to what I wanted. But on IE9, the item.desc which shows up on other browsers is not visible on IE9. I think the code to start with fixing is the last part, the part which appends the suggestions of the autocomplete. Can someone help me out here? Cheers!
You need to upgrade bgiframe.min.js to a later version (3.0 works fine)
https://github.com/brandonaaron/bgiframe
Create a new css class to override the existing jquery ui autocomplete "position":"absolute"
.ui-autocompelte{
"position": "absolute"
....
....
}
New CSS Class
.ui-autocomplete-ie9-fix { position: relative !important; }
and apply this css class after
$("#find").autocompelte({
........
.......
});
if (!$.browser.msie || ($.browser.msie && $.browser.version != 9)) {
$("ul.ui-autocomplete").addClass("ui-autocomplete-ie9-fix");
}
Add below tag after head tag
<meta http-equiv="X-UA-Compatible" content="IE=8" />

How can I add and show a new select value to a jquery combo box autocomplete

I'm using jquery UI autocomplete combobox which is populated with a select box.
Here is the code:
$.widget( "ui.combobox", {
_create: function() {
var input,
self = this,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "",
wrapper = this.wrapper = $( "<span>" )
.addClass( "ui-combobox" )
.insertAfter( select );
input = $( "<input>" )
.appendTo( wrapper )
.val( value )
.addClass( "ui-state-default ui-combobox-input" )
.autocomplete({
delay: 0,
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
select: function( event, ui ) {
ui.item.option.selected = true;
self._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( this ).val( "" );
select.val( "" );
input.data( "autocomplete" ).term = "";
return false;
}
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.appendTo( wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-combobox-toggle" )
.click(function() {
// close if already visible
if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
input.autocomplete( "close" );
return;
}
// work around a bug (likely same cause as #5265)
$( this ).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
input.focus();
});
},
destroy: function() {
this.wrapper.remove();
this.element.show();
$.Widget.prototype.destroy.call( this );
}
});
Here is a screenshot showing the form:
When a user clicks 'add Author' a modal loads for them to create a new Author model object. I want to add and show the newly created author in the jquery UI combobox.
I'm using Rails 3.2 and use a create.js.erb file to control the response from creating the object.

jQuery Combobox unsafe HTML insertion

I tried to use jQuery combobox (fiddle) in my Mozilla Firefox addon. But AMO editors rejected my Addon after reviewing stating that my javascript does unsafe HTML insertion with unsanitized data. Parts of the code stated as unsafe all belong to the code on official jQuery Ui page for combobox. I am also writing the code below. Removing this piece of code throws error if I try to create a combobox.
It makes me wonder why combobox isn't already included in jQuery and why do I have to put this snippet inside my code? Am I doing anything wrong here. Alternatively Can someone suggest me how can I make this code taken from official jquery page safe and sanitized?
(function( $ ) {
$.widget( "ui.combobox", {
_create: function() {
var self = this,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "";
var input = this.input = $( "<input>" )
.insertAfter( select )
.val( value )
.autocomplete({
delay: 0,
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
select: function( event, ui ) {
ui.item.option.selected = true;
self._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( this ).val( "" );
select.val( "" );
input.data( "autocomplete" ).term = "";
return false;
}
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
this.button = $( "<button type='button'> </button>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.insertAfter( input )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-button-icon" )
.click(function() {
// close if already visible
if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
input.autocomplete( "close" );
return;
}
// work around a bug (likely same cause as #5265)
$( this ).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
input.focus();
});
},
destroy: function() {
this.input.remove();
this.button.remove();
this.element.show();
$.Widget.prototype.destroy.call( this );
}
});
})( jQuery );

Selecting a jquery-ui-tab based on its id instead of its index?

Anyone know why the following does not work?
$.each( data.d, function( index, item ) {
// creates the tabs with custom ids
$( "#tabs" ).tabs( "add", "page.aspx?id=" + item.id, item.name )
.find('>ul>li:last')
.attr('id', 'tab_' + item.id);
// creates the buttons
$( "#buttons" ).append( "<input type='button' id='buttona" + item.id + "' value='" + item.name + "'>" );
// link buttons with tabs
$( "#buttona" + item.id ).live('click', function() {
$( "#tabs" ).tabs( "select" , "#tab_" + item.id );
});
});
I am trying to assign id's to the tabs, then select the tabs using their id's.
The above does nothing when a button is clicked and it returns no errors at all.
It works fine when using the index as shown below, but I need to use an id for various reasons:
$.each( data.d, function( index, item ) {
// creates the tabs
$( "#tabs" ).tabs( "add", "page.aspx?id=" + item.id, item.name );
// creates the buttons
$( "#buttons" ).append( "<input type='button' id='button" + index + "' value='" + item.name + "-" + index + "'>" );
// link buttons with tabs
$( "#button" + index ).live('click', function() {
$( "#tabs" ).tabs( "select" , index );
});
});
You can use the index() method to get the index of the tab from the id of its header:
$("#button" + item.id).live("click", function() {
$("#tabs").tabs("select", $("#tab_" + item.id).index());
});
Since index() is called without arguments in the code above, it will return the index of the element relative to its siblings, i.e. the other tab headers.
you can switch the tabs with the id of the tab:
var $tabs = $("#tabs").tabs();
$("button").click(function() {
$tabs.tabs( "select", "#tabs-6" );
});
It seems to me that .index() returns an index from 1 so that if I have 3 tabs and want to select the third one, I should return :
$("#button" + item.id).live("click", function() {
$("#tabs").tabs("select", $("#tab_" + item.id).index()-1);
});

Resources