Render html element present inside jquery autocomplete data - javascript

I am making use of jQuery autocomplete with remote data source. Remote data contains HTML tags. Sample data is of form:
[
"ABC <span>XYZ</span>",
"PQR <span>LMN</span>",
];
Autocomplete dropdown contain output like
ABC <span>XYZ</span>
PQR <span>LMN</span>
I want HTML tags to get render and dropdown to show output like
ABC XYZ
PQR LMN
http://jsfiddle.net/ac112jmx/2/

You can override it using Custom Display use .autocomplete("instance")._renderItem method.
instance()
Retrieves the autocomplete's instance object. If the element does not have an associated instance, undefined is returned.
_renderItem( ul, item )
Method that controls the creation of each option in the widget's menu. The method must create a new <li> element, append it to the menu, and return it.
Code
$("#tags").autocomplete({
source: availableTags,
select: function (event, ui) {
console.log(ui.item);
$("#tags").val(ui.item.label);
return false;
}
}).autocomplete( "instance" )._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
DEMO

You can use $.parseHTML(str)
var dropdown = $.parseHTML('ABC <span>XYZ</span>');
Check the following example:
$('#wrp').html($.parseHTML('This is a <b>Bold text</b>'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="wrp"></span>

Related

Use multiselect with dynamically generated select

I am trying to use the multiselect plugin I found on here:
How to use Checkbox inside Select Option
The question above is for a <select> with hard coded <options>.
The <select> I am using generates <options> using jQuery and PHP with this function:
function initializeSelect($select, uri, adapt){
$.getJSON( uri, function( data ) {
$select.empty().append($('<option>'));
$.each(data, function(index, item) {
var model = adapt(item);
var $option = $('<option>');
$option.get(0).selected = model.selected;
$option.attr('value', model.value)
.text(model.text)
.appendTo($select);
});
});
};
initializeSelect($('#salesrep'), 'process/getSalesReps.php', function (item) {
return {
value: item.final_sales_rep,
text: item.final_sales_rep
}
});
I have used the above function several times in different projects, as it successfully creates all of the options brought in by the PHP process. Unless requested, I will not show the code for the process. Just know I am indeed retrieving a group of names and displaying them in the dropdown.
Right beneath the function above is where I call the multiselect feature:
$('select[multiple]').multiselect();
$('#salesrep').multiselect({
columns: 1,
placeholder: 'Select Reps'
});
The HTML for the select is as follows:
<select class="form-control" name="salesrep[]" multiple id="salesrep"></select>
Using all of the above, the output looks like this:
Upon inspecting the element, I can see all of the sales reps names. This tells me that the initializeSelect function is working properly.
Therefore I think the issue must have something to do with the multiselect.
Ajax calls are asynchronous. You call multiselect() before the ajax call has had time to complete and therefore the option list is still empty at the point you call the multiselect() function.
Either move the $('#salesrep').multiselect({.. bit to inside the getJSON method or call the multiselect refresh function after the option list has been populated as I am doing here. (Untested.)
function initializeSelect($select, uri, adapt){
$.getJSON( uri, function( data ) {
$select.empty().append($('<option>'));
$.each(data, function(index, item) {
var model = adapt(item);
var $option = $('<option>');
$option.get(0).selected = model.selected;
$option.attr('value', model.value)
.text(model.text)
.appendTo($select);
});
//now that the ajax has completed you can refresh the multiselect:
$select.multiselect('refresh');
});
};
initializeSelect($('#salesrep'), 'process/getSalesReps.php', function (item) {
return {
value: item.final_sales_rep,
text: item.final_sales_rep
}
});
$('select[multiple]').multiselect();
$('#salesrep').multiselect({
columns: 1,
placeholder: 'Select Reps'
});

Appending elements to a DIV from a JSON array in Polymer

I'm struggling right now with inserting a set of divs into a core-header-panel inside a paper-shadow in Polymer. I am getting a set of values from a JSON array and I need to create a div with HTML content (eventually checkboxes) for each of the values. Here's the relevant snippet of code:
<paper-shadow class="card upload-options-box" z="1">
<core-header-panel flex id="graphHeaderList">
<core-toolbar class="upload-option-header">
<span flex>Variable</span>
</core-toolbar>
<core-label horizontal layout> // this is all just an example of what I eventually want to insert
<paper-checkbox for></paper-checkbox>
<div vertical layout>
<h4>MakeCircuitCreated</h4>
</div>
</core-label> // end of example of insert
</core-header-panel>
</paper-shadow>
and JQuery:
function addHeaders(){
$.getJSON('http://myURL/getDataHeaders', function(data) {
var headerArray = [];
$.each(data, function(key, val) {
$('#graphHeaderList').append("<div id='" +val +"'></div>");
console.log(val);
headerArray.push(val)
});
console.log(headerArray);
});
}
window.onload = addHeaders; //grabs the header values when the page is loaded
My JSON:
{
"headers": [
"MakeSpawnFish",
"MakeEndGame",
"MakeModeChange",
"MakeConnectComponent",
"MakeCircuitCreated",
"MakeStartGame",
"MakeSnapshot",
"MakeResetBoard",
"MakeAddComponent",
"MakeCaptureFish",
"MakeRemoveComponent",
"MakeDisconnectComponent"
]
}
It appears to me your $.each is calling the wrong thing.
In your json file you have a key called headers. When your each function iterates, it gets 1 key and adds it's members, which is an array, to the div. I tested it and got one div with every single member as it's id!
So you may need to nest a second each function to be called on the inner array
$.each(data, function(key, val) {
$.each(val, function(index,value){
$('#graphHeaderList').append("<div id=" + "'" + value + "'" + "></div>");
console.log(value);
headerArray.push(value);
}
);
https://api.jquery.com/jquery.each/
Your code:
$('#graphHeaderList').append("<div id='" +val +"'></div>");
Won't work, because jQuery can't find the element in its scope. However, polymer automatically creates id element references through its automatic node finding feature:
this.$.graphHeaderList
So it should work as expected if you use:
$(this.$.graphHeaderList).append("<div id='" +val +"'></div>");

How to dynamically construct html tag attriburtes with json data?

I am having (Strigified) json data in a variable called test. I am constructing html elements dynamically and also I want json data to be inserted in an element attribute.
var templateHtml = "":
$.each(loopValues, function(Key, Value) { // Loops which constructs dynamic data
var test = '{"type": "page"}'; // this is the json data which need to be appended as data-all attribute value.
templateHtml = templateHtml.concat("<a data-all="+ test +" href='javascript:;' class='icon' id='TestTt'></a>");
}
$("#sortable1").html(templateHtml);
After executing these lines, when I see the constructed element, It is totally scrambled. How to get a well formatted json data in a element attribute ?
I do not want to append json data on attribute using jquery after constructing html. I want this functionality at html construction time.
I refered
http://gabrieleromanato.name/jquery-binding-animation-data-to-elements-with-json/
http://api.jquery.com/jQuery.parseJSON/
Any Idea ?
First, your code miss some syntax element :
var templateHtml = ""; // use ; not :
$.each(loopValues, function (Key, Value) { // Loops which constructs dynamic data
var test = '"{type": "page"}'; // this is the json data which need to be appended as data-all attribute value.
templateHtml = templateHtml.concat("<a data-all=" + test + " href='javascript:;' class='icon' id='TestTt'></a>");
}); //close the loop call
Then you need to add single quotes around your test variable when you append it. I suggest you choose where to use single quotes or doubles and stick to the choice permanently. I personnally use double quotes in HTML and single quotes in JS :
var templateHtml = '';
$.each(loopValues, function (Key, Value) { // Loops which constructs dynamic data
var test = "{type: 'page'}"; // this is the json data which need to be appended as data-all attribute value.
//since its JSON i use single quote inside but double outside.
templateHtml = templateHtml.concat('<a data-all="' + test + '" href="javascript:;" class="icon" id="TestTt"></a>');
});
FIDDLE here
What you need is creating elements with jQuery with json as parameters.
For example creating a simple table
var $table = new $('<table>', { 'cellpadding' : '5', 'cellspacing' : '4' });
var $tr = new $('<tr>');
var $td = new $('<td>', { 'class' : 'test' });
$td.text('cell contents');
$tr.append($td);
$table.append($tr);
$('body').append($table);
You can keep your json in DOM without data- attribute, just use:
$("#sortable1").html("<a href='javascript:;' class='icon' id='TestTt'></a>");
$( "#sortable1 > a" ).data( 'all', test );
According to jQuery .data() API. Data value can be any JavaScript type.
To get this JSON you will need just to write:
console.log( $( "#sortable1 > a" ).data( 'all' ) );
UPDATE:
But better is to add data at creation proccess:
$.each(loopValues, function(Key, Value) { // Loops which constructs dynamic data
$( "#sortable1" ).append( $( "<a/>" ).addClass( "icon" ).data( "all", {"type": "page"} ).attr( "id", "TestTt" ) );
});

Trying to get Jquery working with dynamic select forms in Rails and Active Admin

I'm trying to update a select box based on another..
In my active admin resource, I did the following just for some test data:
controller do
def getcols
list = new Hash
list = {"OPTION1" => "OPTION1", "OPTION2" => "OPTION2"}
list.to_json
end
end
In active_admin.js I have the following
$('#worksheet_type').change(function() {
$.post("/admin/getmanifestcols/", { ws_type: $(this).val() }, function(data) {
populateDropdown($("#column_0"), data);
});
});
function populateDropdown(select, data) {
 select.html('');
alert('hi');
$.each(data, function(id, option) {
select.append($('<option></option>').val(option.value).html(option.name));
});      
}
The above is working in the sense that when my primary select box is changed, the jquery is called and I even get the alert box of 'hi' to be called. However, it's not replacing the contents of the select box with my test OPTION1 and OPTION2 data.
I think I'm passing in the JSON wrong or something, or it's not being read.
What am i missing?
It looks to me as if you're not properly iterating over the map.
What about:
$.each(data, function(value, name) {
select.append($('<option></option>').val(value).html(name));
});
?

jQuery UI autocomplete with custom data from Facebook Graph API friends

i want my facebook graph api /me/friends list in an autocomplete field. I want choose my friend, select one of them end have its ID.
Facebook response with a "data" json object with name and id. Perfect!
Some code:
$(document).ready(function(){
FB.api('/me/friends', function(fbresponse){
$("#input_13").autocomplete({
source : function(request, response){
response($.map(fbresponse.data, function(e){
return{
id : e.id,
name : e.name
}
}))
},
select : function(event, ui){
alert(ui.item.name);
$("#input_13").val(ui.item.name);
$("#input_10").val(ui.item.id);
return false;
}
}).data("autocomplete")._renderItem = function(ul, item){
return $("<li></li>")
.data("item.autocomplete", item)
.append( $("<a></a>").html(item.name) )
.appendTo(ul);
};
});
});
Results is at 90%, when I begin typing, the list of my friends appears but it's order from the first to the end, it's not filtered.
Example:
My list complete is:
marco
massimo
marino
mimmo
simone
sara
sonia
when I begin with "s" should result only
simone
sara
sonia
but the result list does not change.
What's happen?
Thanks a lot.
As your source property is pointing to a function it is called ever the plugin needs the datasource, the problem is: the FB Graph API don't accept a "term" param when searching for friends so it returns always the same data based on your input. What you need is something like this:
var makeItems = function(fbresponse) {
return $.map(fbresponse, function(item) {
return {
label: item.name,
value: item.id,
}
});
};
var setAutoComplete = function(parsed_items) {
$("#input_13").autocomplete({
source : parsed_items,
select : function(event, ui){
alert(ui.item.name);
$("#input_13").val(ui.item.name);
$("#input_10").val(ui.item.id);
return false;
}
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append( $("<a></a>").html(item.name) )
.appendTo(ul);
};
};
FB.api('/me/friends', function(fbresponse) {
setAutoComplete(makeItems(fbresponse.data));
});
It will make only one request, will get all the friends and set a variable with an array of parsed items so the filter can act in the array.
I hope it help you.
take a look at this code example, its working fine.
http://blogs.microsoft.co.il/blogs/alon_nativ/archive/2011/05/30/search-facebook-friends-with-jquery-autocomplete.aspx

Categories