Materialize chips initialization - javascript

I would like to add dynamically some materialize chips.
$('.chips-initial').material_chip({
data: [{
tag: 'Apple'
}, {
tag: 'Microsoft'
}, {
tag: 'Google'
}]
});
Like above but the values I want to give are dynamic.
How can I create an data object like above to pass it as parameter?
Thank you in advance

Basically what happens here is when the page loads it populates the text string values found in metaTags that were inserted into a hidden field from the database. The for loop iterates into the necessary chips-initial.
var tagsMeta = [];
//alert(tagsMeta);
var tagsString = document.getElementById('metaTags').value;
//alert(tagsString);
var tagsArray = tagsString.split(',');
for(i=0; i < tagsArray.length; i++) {
tagsMeta.push({tag: tagsArray[i]});
}
$('.chips-initial').material_chip({
data: tagsMeta
});

As I commented, you could create your own array of values and pass that to data. This might look like:
var myData = [
{
tag: 'iPhone'
}, {
tag: 'Windows Phone'
}, {
tag: 'Android Phone'
}
];
$('.chips-initial').material_chip({
data: myData
});
Wokring Example: https://jsfiddle.net/Twisty/en6r0ucb/

I found solution
var authData = [];
var tag = {};
tag["tag"] = yourString;
authData.push(tag);
$('.chips-initial').material_chip({
data: authData
});

Related

Can Javascript read a title tag from a HTML doc and ignore that value in an array?

I am trying to create a "random article" menu with Javascript at the bottom of blog posts.
I am wondering if there is a way to get the script to read the of the current article so I can omit that from the array and not have the article link to itself.
I get that I'll have to change the way the array data is stored, just need to know if I can make JS read the HTML tag.
Thanks!
//array is [<title>, <img src>]
var arts = [
["Santorini", "santo1_450h"],
["Penang", "penang1"],
["Porto", "Porto6_450h"],
["Crete", "Crete5"],
["Langkawi", "langkawi2"],
["Singapore", "singapore1"]
];
var clone = [];
function shuffle(array) {
//shuffles the array
return clone;
}
shuffle(arts);
function createRandArts() {
//creates a bunch of HTML content
}
createRandArts();
You can use document.title to get the title of the current page and then loop through your array and remove it
Here is how you read a title tag
var list = document.getElementsByTagName("TITLE")[0]
Yes you can use JS to read the document title, and then loop through your array, omitting that title if found.
Here's an example using an array of objects instead:
var arts = [
{
title: "Santorini",
src: "santo1_450h"
},
{
title: "Penang",
src: "penang1"
},
{
title: "Porto",
src: "Porto6_450h"
},
{
title: "Crete",
src: "Crete5"
},
{
title: "Langkawi",
src: "langkawi2"
},
{
title: "Singapore",
src: "singapore1"
}
];
function shuffle(array) {
let clone = [];
clone = arts.filter(e => e.title !== document.title);
//shuffle clone here
return clone;
}

ZingChart X-axis labels showing as numbers instead of strings

I am using the ZingChart library to graph results from an API call. When I pass in a normal array for the "values" field of the chart data object, everything works fine. However, when I pass in an array made from Object.keys(titleSet) (where titleSet is a normal Javascript object), the graph displays as follows:
Example Chart
As you can see, the x-axis is now labeled with numbers instead of the array of strings. But when I print out the the result of Object.keys(titleSet) vs. passing in a normal array, they both appear to be the same in the console. Can anyone help me figure out what I'm doing wrong?
//List of movies inputted by the user
var movieList = [];
var movieSet = {};
var IMDBData = {
"values": [],
"text": "IMDB",
};
var metascoreData = {
"values": [],
"text": "Metascore"
};
var RTMData = {
"values": [],
"text": "Rotten Tomatoes Meter"
};
var RTUData = {
"values": [],
"text": "Rotten Tomatoes User"
};
var chartData = {
"type":"bar",
"legend":{
"adjust-layout": true
},
"plotarea": {
"adjust-layout":true
},
"plot":{
"stacked": true,
"border-radius": "1px",
"tooltip": {
"text": "Rated %v by %plot-text"
},
"animation":{
"effect":"11",
"method":"3",
"sequence":"ANIMATION_BY_PLOT_AND_NODE",
"speed":10
}
},
"scale-x": {
"label":{ /* Scale Title */
"text":"Movie Title",
},
"values": Object.keys(movieSet) /* Needs to be list of movie titles */
},
"scale-y": {
"label":{ /* Scale Title */
"text":"Total Score",
}
},
"series":[metascoreData, IMDBData, RTUData, RTMData]
};
var callback = function(data)
{
var resp = JSON.parse(data);
movieSet[resp.Title] = true;
//Render
zingchart.render({
id:'chartDiv',
data:chartData,
});
};
Full Disclosure, I'm a member of the ZingChart team.
Thank you for updating your question. The problem is you have defined your variable movieSet before the variablechartData. When parsing the page, top down, it is executing Object.keys({}) on an empty object when creating the variable chartData. You should just directly assign it into your config later on chartData['scale-x']['values'] = Object.keys(moviSet).
var callback = function(data)
{
var resp = JSON.parse(data);
movieSet[resp.Title] = true;
//Render
zingchart.render({
id:'chartDiv',
data:chartData,
});
};
There is a problem with the above code as well. It seems you are calling render on the chart every time you call this API. You should have one initial zingchart.render() and then from there on out use our API. I would suggest setdata method as it replaces a whole new JSON packet or modify method.
I am making some assumptions on how you are handling data. Regardless, check out the following demo
var movieValues = {};
var myConfig = {
type: "bar",
scaleX:{
values:[]
},
series : [
{
values : [35,42,67,89,25,34,67,85]
}
]
};
zingchart.render({
id : 'myChart',
data : myConfig,
height: 300,
width: '100%'
});
var callback = function(data) {
movieValues[data.title] = true;
myConfig.scaleX.values = Object.keys(movieValues);
zingchart.exec('myChart', 'setdata', {
data:myConfig
})
}
var index = 0;
var movieNamesFromDB = ['Sausage Party', 'Animal House', 'Hot Rod', 'Blazing Saddles'];
setInterval(function() {
if (index < 4) {
callback({title:movieNamesFromDB[index++]});
}
},1000)
<!DOCTYPE html>
<html>
<head>
<!--Assets will be injected here on compile. Use the assets button above-->
<script src= "https://cdn.zingchart.com/zingchart.min.js"></script>
<script> zingchart.MODULESDIR = "https://cdn.zingchart.com/modules/";
</script>
<!--Inject End-->
</head>
<body>
<div id='myChart'></div>
</body>
</html>
If you noticed in the demo, the length of scaleX.values determines how many nodes are shown on the graph. If you change values to labels this wont happen.

Accessing object data in datatables through get function

I am trying to create an object that I can modify as per
Datatables - Data
I use the following code to create my object
function projectData(projid,projdesc,descdet){
this._projid = 'HTML1'
this._projdesc = 'HTML2'
for(var i=0;i<=7;i++){
this['_day'+i] = 'HTML3';
}
this.projid = function(){
return this._projid
}
this.projdesc = function(){
return this._projdesc
}
this.day0 = function(){ // More of these for day (0-7)
return this._day0
}
}
Then I use the following table initialization. (prjData is an array of New projectData objects)
var table = $('#table-ProjectHours').DataTable({
data: prjData,
"columns": [
{ data: 'projid',"visible": true},
{ data: 'projdesc',"width": "45%" },
{ data: 'day0',"orderDataType": "dom-text-numeric" },
{ data: 'day1',"orderDataType": "dom-text-numeric" },
{ data: 'day2',"orderDataType": "dom-text-numeric" },
{ data: 'day3',"orderDataType": "dom-text-numeric" },
{ data: 'day4',"orderDataType": "dom-text-numeric" },
{ data: 'day5',"orderDataType": "dom-text-numeric" },
{ data: 'day6',"orderDataType": "dom-text-numeric" },
{ data: 'day7',"orderDataType": "dom-text-numeric" }
]
});
I access my table through
var dto = $('#table-ProjectHours').DataTable().data();
I get my objects as seen here:
What I do not understand is why when I attempt to do dto[0].day0 I do not get _day0 --- I just get the function string.
I can access the data through _day0 but it seems wrong...
Try rows().data() https://datatables.net/reference/api/rows().data()
e.g.
var table = $('#example').DataTable();
var data = table
.rows()
.data();
alert( 'The table has '+data.length+' records' );
In order to set data in jquery-datatables you must use .row(index).data(obj) or .cell(selector).data(obj).
You can also use row(index).day0() and if you write a set portion of your method you can set the data like row(index).day0(thing_to_set) You must call row(index).invalidate after changing the data for it to appear correctly.
In this particular situation, .day0 must be called as .day0() since it is a method.

Dynamic creation of multilevel Javascript object for jQuery-jTable

jTable (jTable.org) layout is defined by the code below. I want to build it dynamically (based on AJAX return from a database query).
{
title: 'My Dynamic Title',
fields: {
id: {
title: 'ID'
},
salesperson: {
title: 'Salesperson'
},
pivot1: {
title: '2012-01'
},
pivot2: {
title: '2012-02'
},
pivot3: {
title: '2012-03'
}
}
}
The data being displayed is a pivot table and so the number of columns and their titles will change. Is it possible for me to dynamically modify the fields section above? e.g., to have four pivot columns with relevant column titles.
Answer
I figured it out thanks to Barmar and extensive reading. The trick is to insert a new object at each level. Pop this into jsfiddle.net and you can see the result. It will programmatically create the object above.
var myobj = {}; //description for jquery-jtable configuration.
var colnames = ['pivot1', 'pivot2', 'pivot3'];
var titles = ['2012-01', '2012-02', '2012-03'];
myobj['title'] = "My Dynamic Title";
myobj['fields'] = {}; //create a second level under 'fields'.
myobj.fields['id'] = {title: 'ID'};
myobj.fields['salesperson'] = {title: 'Salesperson'};
for(i = 0; i < colnames.length; i++) {
myobj.fields[colnames[i]] = {}; //create a third level under column name.
myobj.fields[colnames[i]].title = titles[i];
}
alert(JSON.stringify(myobj, null, 4));
I don't see a method to change the field specification dynamically. But if you're modifying the table, you can simply destroy the old jTable and reinitialize it:
$("#TableContainer").jtable("destroy");
$("#TableContainer").jtable({
// New options
});
If there are some options that will stay consistent across all instances, you can use a variable to hold the options:
var jtable_options = {
title: "My Table Title",
fields: {}
};
Before you initialize a jtable, you do:
jtable_options.fields = {
id: { title: 'ID' },
salesperson: { title: 'Salesperson' }
...
};
$("#TableContainer").jtable(jtable_options);

Append results from MULTIPLE arrays to the INITIALLY GENERATED ul after click, how can this be done?

So, I have a bunch of sources for Autocomplete, like this:
var search1 = [{
search: "authors1"
}, {
search: "autocomplete1"
}, {
search: "automatic1"
}];
var search2 = [{
search: "authors2"
}, {
search: "autocomplete2"
}, {
search: "automatic2"
}];
var search3 = [{
search: "authors3"
}, {
search: "autocomplete3"
}, {
search: "automatic3"
}];
I MUST store data in different arrays, so please don't suggest me to join them.
HTML:
<input data-source="search1,search2,search3" type="text" value="" />
<div id="loadingmsg" style="display:none">Searching...</div>
I'd like to have a recursive function that will come through all the sources specified in "data-source" attribute and append results to one menu. For example, when I type "auth", I want to see this:
#loadingmsg reveals itself.
The resulting menu (containing "authors1", "authors2" and "authors3") shows up.
#loadingmsg disappears.
Is it possible?
With <input data-source="1,2,3" />
//bind a response to typing for each of these inputs
$("img[data-source]").on('keyup', function () {
//get typed value
var value = $(this).val();
//clear the current menu
$("#menu").empty();
//show loading image (probably ineffective)
$("#loadingimg").show();
//iterate over source keys acquired from <input> data
$.each($(this).data('source').split(','), function () {
//iterate over corresponding object in `search`
$.each(search[this], function () {
//typed value matches string
if (this.indexOf(value) > -1) {
$("#menu").append('<span>' + this + '</span>');
}
});
});
$("#loadingimg").hide();
});

Categories

Resources