I need to get data from Materialize CSS chips, but I don't know, how.
$('.chips-placeholder').material_chip({
placeholder: 'Stanici přidíte stisknutím klávesy enter',
secondaryPlaceholder: '+Přidat',
});
function Show(){
var data = $('.chips-placeholder').material_chip('data');
document.write(data);
}
<!-- Added external styles and scripts -->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/js/materialize.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css">
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- HTML body -->
<div class="chips chips-placeholder"></div>
<button onclick="Show()" type="button">Show</button>
So, to access to the data's chip you just have to do this:
var data = $('#id of your chips div').material_chip('data');
alert(data[0].tag);`
'0' is the index of your data (0, 1, 2 , 3, ...).
'tag' is the chip content. You can also get the id of your data with '.id'.
To get data from Materialize CSS chips, use the below code.
$('#button').click(function(){
alert(JSON.stringify(M.Chips.getInstance($('.chips')).chipsData));
});
They appear to have changed the method available in the latest version.
The documentation suggests that you should be able to access the values as properties of the object, but I’ve spent an hour looking, not getting anywhere.
Until the following happened
$('.chips-placeholder').chips({
placeholder: 'Enter a tag',
secondaryPlaceholder: '+Tag',
onChipAdd: (event, chip) => {
console.log(event[0].M_Chips.chipsData);
},
During the onChipAdd event I was able to access the event. Within this object was an array of tags.
I know this isn't the documented way, however there is only so much time a client will accept when it comes billing and I must move on.
This worked great for me
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.chips');
var instances = M.Chips.init(elems, {
placeholder: "Ajouter des Tags",
secondaryPlaceholder: "+tag",
onChipAdd: chips2Input,
onChipDelete: chips2Input,
Limit: 10,
minLength: 1
});
function chips2Input(){
var instance = M.Chips.getInstance(document.getElementById('chip1')), inpt = document.getElementById('myInputField');
inpt.value = null;
for(var i=0; i<instance.chipsData.length; i++){
if(inpt.value == null)
inpt.value = instance.chipsData[i].tag;
else{
inpt.value += ','+instance.chipsData[i].tag; //csv
}
}
console.log('new value: ', inpt.value);
}
});
</script>
Related
This is my first post, hoping someone can help me:
I wish to build a web project, where all the HTML elements are stored in database and taken from it to build the web page.
i found a problem with the buttons, i cannot find a way to store the function for a button, i´m using Jquery to build the elements, for now the test element definitions are simulated in some arrays i left at the start of my Js file, the only way i can make the buttons to work is if the functions are hardcoded in the Js file, is there a way for me to bring the functions from database too? and having them in an array?
this is my project sample:
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!--script src="functions.js"></script-->
<script src="system.js"></script>
<!--script src="elements.js"></script-->
</head>
<body>
<body onload="addElements()">
<div id="div1"></div>
</body>
</html>
JS File
/**
VARIABLE DEFINITIONS
THESE ARE SUPPOSED TO COME FROM A DATABASE
STILL UNKNOWN HOW TO BRING THE FUNCTIONS, AS STRING THEY ARE NOT ALLOWED. FOR NOW THERE ARE TEST FUNCTIONS.
**/
let buttonIds = ['btn1', 'btn2'];
let buttonText = ['Show Text', 'Show HTML'];
let buttonFunc = [alert1, alert2];
//let buttonFunc = ['alert("Hi");', 'alert("Hello");'];
let paragraphs = ['This is some <b>bold</b> text in a paragraph.', 'another <b>bold</b> test'];
//HELPER FUNCTIONS
// **** THESE ARE SUPPOSED TO COME FROM DATABASE, UNKNOWN HOW TO DO IT. ****
function alert1() {
alert("Hi");
}
function alert2(){
alert("Hello");
}
function addElements(){
for(var p=0; p<paragraphs.length; p++){ addParagraphs('#div1', paragraphs[p]); }
for(var i=0; i<buttonIds.length; i++) { createButton( '#div1', buttonIds[i] , buttonText[i]); }
}
// ANY ELEMENTS FUNCTION IS DEFINED HERE ONCE THE PAGE IS LOADED.
$(document).ready(function(){
for(var x=0;x<buttonIds.length; x++){ activateButton(buttonIds[x], buttonFunc[x]); }
});
//HELPER FUNCTIONS USED TO BUILD THE HTML ELEMENTS ON THE MAIN PAGE.
function addParagraphs(location, text){
$(location).append('<p id="test">'+text+'</p>');
}
function createButton(location, id, text){
var definition;
definition = "<button id="+id+">"+text+"</button>";
$(location).append(definition);
}
function activateButton(buttonId, functionName){
var composedId = "#"+buttonId;
$(composedId).click(functionName);
}
You can generate Javascript file serverside with all the funcions you need.
Supposing Node.js you can do something like this:
expressApp.get("some.js", (req, res) => {
getDataFromDatabase() // depends on your database
.then(data => {
let body = 'function your_fn () { alert("'+ JSON.stringify(data) +'")}';
res.send(body);
})
});
One approach is use an object to store the functions in javascript and use property names stored in db to associate which function to use for which element.
Without knowing more about your use case it is hard to really help design a proper system to use
Following is a very basic example
// functions stored in js file
const funcs = {
f1: function(e){ console.log('func one called , id = ', this.id)},
f2: function(e){ console.log('func 2 called , id = ', this.id)}
}
// data from database
const elems = [
{id: 1, className: 'one', func:'f1', text:'Item 1'},
{id: 1, className: 'two', func:'f2', text:'Item 2'}
]
elems.forEach(e => {
const $el= $('<div>', {id: e.id, class: e.className, text:e.text, click: funcs[e.func]})
$('body').append($el);
});
div {margin:1em;}
.one {color:red;}
.two {color:green;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong>Click on items</strong><br><br>
I've a problem with plotting an number array in Plotly. So, we can skip to subject without further ado.
Here is HTML code:
<script src="plotly.min.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/7.2.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.0/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.1/firebase-database.js"></script>
<div class="navbar"><span>Analog Plotter by remidosol</span></div>
<div class="wrapper">
<div id="chart"></div>
<script src="FireConfig.js"></script>
<script>
Plotly.plot('chart',[{
y:[analogval()],
type:'line'
}]);
var cnt = 0;
setInterval(function(){
Plotly.extendTraces('chart',{ y:[[analogval()]]}, [0]);
cnt++;
if(cnt > 300) {
Plotly.relayout('chart',{
xaxis: {
range: [cnt-300,cnt]
}
});
}
},15);
</script>
</div>
</body>
How can I plot number ARRAY that read from Firebase? I changed getData function's return code, once.(like I placed a num array parameter to getData, but it didn't make the plot.ly code work to plot data).
I could read data from Firebase but i couldn't plot it.
Here is view of my website and console:
It reads data but can't plot.
Would you help me please? What's wrong with this code? BTW, Firebase config block is okay, i changed it before create this subject.
I'm waiting for your help. Thank you from now.
Edit:
I can get data and convert it to number by replace and slice methods. It's correct now. But the plot.ly code still don't plot data line.
Following aforementioned function, here is the code below:
function analogval(){
databaseiot.orderByChild("analog").on('value', function(dataSnapshot) {
var arru = dataSnapshot.val().analog;
arru.toString();
arru = arru.replace(/\\r/g,'');
arru = arru.slice(1, 4);
arru = Number(arru);
console.log(arru);
return arru;
//arru = data.val().analog.split(",").map(Number);
})}
The issue is in your analogval() function. If I'm not mistaken, your current implementation of analogval () doesn't return anything. Your return statement is inside of the callback function that you passed to the .on() method. What you need is to have your analogval() function to return the value of the array.
One way to do this is to create a variable (e.g. array) visible to analogval() and set the value of array to be what you read from Firebase, then return array from analogval():
var array;
function analogval(){
databaseiot.orderByChild("analog").on('value', function(dataSnapshot) {
var arru = dataSnapshot.val().analog;
arru.toString();
arru = arru.replace(/\\r/g,'');
arru = arru.slice(1, 4);
arru = Number(arru);
console.log(arru);
array = arru;
});
return array;
}
I think I have a syntax error that may be affecting other things on my store.
This error just started popping up:
(index):1544 Uncaught SyntaxError: Unexpected token <
Line 1544 of index, as I see it in the console under sources, has this:
1544 <script text="text/javascript">
I have never seen 'text=text' so I am wondering if that is what is causing the error. On top of that our product thumb nails wont respond, and there seems to be other negative effects as well, here are the other errors:
ERROR: product.functions.js:382 Uncaught ReferenceError: ProductThumbWidth is not defined
ERROR: product.functions.js:291 Uncaught ReferenceError: CurrentProdThumbImage is not defined(index):1609 Uncaught
ERROR: ReferenceError: ShowVariationThumb is not defined
I want to take care of the first syntax error message before I move on to the rest, and I am thinking that fixing it may fix other things and I think it is coming from here, ProductDetails.html. There may be a missing script tag, but I have never touched this file so I don't know why it would happen all of a sudden, and with the code that is commented out, it seems like it shouldn't affect it.
<script type="text/javascript">
var google_tag_params = {
ecomm_prodid: %%GLOBAL_ProductId%%,
ecomm_pagetype: 'product',
ecomm_totalvalue: parseFloat('%%GLOBAL_ProductPrice%%'.replace("$","").replace(",",""))
};
</script>
<link rel="stylesheet" type="text/css" href="%%GLOBAL_CdnAppPath%%/javascript/jquery/themes/cupertino/ui.all.css?%%GLOBAL_JSCacheToken%%" />
<link rel="stylesheet" type="text/css" media="screen" href="%%GLOBAL_productAttributesCssPath%%?%%GLOBAL_JSCacheToken%%" />
<script type="text/javascript" src="%%GLOBAL_jQueryUIPath%%"></script>
<script type="text/javascript" src="%%GLOBAL_CdnAppPath%%/javascript/jquery/plugins/jquery.form.js?%%GLOBAL_JSCacheToken%%"></script>
<script type="text/javascript" src="%%GLOBAL_CdnAppPath%%/javascript/product.attributes.js?%%GLOBAL_JSCacheToken%%"></script>
<script type="text/javascript" src="%%GLOBAL_CdnAppPath%%/javascript/jquery/plugins/jCarousel/jCarousel.js?%%GLOBAL_JSCacheToken%%"></script>
%%SNIPPET_ProductImageZoomer%%
<script type="text/javascript">//<![CDATA[
var ThumbURLs = new Array();
var ProductImageDescriptions = new Array();
var CurrentProdThumbImage = %%GLOBAL_CurrentProdThumbImage%%;
var ShowVariationThumb =false;
var ProductThumbWidth = %%GLOBAL_ProductThumbWidth%%;
var ProductThumbHeight = %%GLOBAL_ProductThumbHeight%%;
var ProductMaxZoomWidth = %%GLOBAL_ProductMaxZoomWidth%%;
var ProductMaxZoomHeight = %%GLOBAL_ProductMaxZoomHeight%%;
var ProductTinyWidth = %%GLOBAL_ProductMaxTinyWidth%%;
var ProductTinyHeight = %%GLOBAL_ProductMaxTinyHeight%%;
%%GLOBAL_ProdImageJavascript%%
//Don't enable Cloud Zoom (product image zoom) on touch device
//Mouseenter/Mouseover events are not ideal for touch devices
//for more info search for this code in /script/main.js
<script type="text/javascript">
var _learnq = _learnq || [];
var item = {
Name: "%%GLOBAL_ProductName%%",
ProductID: %%GLOBAL_ProductId%%,
ImageURL: "%%GLOBAL_CurrentProdThumbImage%%",
URL: window.location.origin + window.location.pathname,
Brand: "%%GLOBAL_BrandName%%",
Price: "%%GLOBAL_ProductPrice%%",
CompareAtPrice: "%%GLOBAL_RetailPrice%%"
};
_learnq.push(['track', 'Viewed Product', item]);
_learnq.push(['trackViewedItem', {
Title: item.Name,
ItemId: item.ProductID,
ImageUrl: item.ImageURL,
Url: item.URL,
Metadata: {
Brand: item.Brand,
Price: item.Price,
CompareAtPrice: item.CompareAtPrice
}
}]);
</script>
<script type="text/javascript">
if (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0)){
var ShowImageZoomer = false;
} else {
var ShowImageZoomer = %%GLOBAL_ShowImageZoomer%%;
}
var productId = %%GLOBAL_ProductId%%;
//]]></script>
Here are screens of the console errors, and sources tab:
Any help is much appreciated!
Without seeing you whole page I'm only guessing, but from the error it looks like you are already inside a <script> tag on line 1544.
Double check your sources, maybe you are not closing a previous <script> tag.
After that you should use type="text/javascript" albeit it's the default and not necessary, you can just use <script>...</script>.
Change
<script text="text/javascript">
to
<script type="text/javascript">
it's type= not text=
Hoi folks, i am not confirm to js. My Problem ist if i define an array for autocomplete in the code it works, if i use an json-array( also from an external source) it dosent. What am i doing wrong ?
jsonData='{"kantone":["VD","FR","GE"]}
var alternate=["TG","ZG","ZH"];
window.availableKanton = JSON.parse(jsonData);
$(function() {
$( "#startkanton" ).autocomplete({
source: window.availableKanton.kantone // dont work if i take the alternate it does
});
});
I pasted your code into the snippet below, and it's working.
The only thing I had to do was to close the string (by putting a ') into the first line.
var jsonData = '{"kantone":["VD","FR","GE"]}';
var alternate = ["TG", "ZG", "ZH"];
window.availableKanton = JSON.parse(jsonData);
$(function() {
$("#startkanton").autocomplete({
source: window.availableKanton.kantone // working
});
});
<link href="https://code.jquery.com/ui/1.11.4/themes/black-tie/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<input id="startkanton">
When using list.js and tabletop for a sortable table taken from a Gdoc, I get the error: "Uncaught TypeError: Cannot read property 'childNodes' of undefined" on the first line of list.js.
Because the website I work for can only have JS uploaded, I need to write all my html using js or jquery, so it's a bit wonky. I think the error is being thrown because of the order I have everything, but I have tried moving things around to no avail. Everything is working other than the sorting.
Thanks!
HTML file
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="list.js-master/dist/list.min.js"></script>
<script type="text/javascript" src="src/tabletop.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="tablesetter"></div>
</body>
<script type="text/javascript">
var url = 'url to gdoc here';
$(document).ready( function(){
Tabletop.init( {key: url, callback: showInfo, parseNumbers: true} )})
function showInfo(data, tabletop){
$("#tablesetter").append('<h2>Table Working</h2><table><thead><th class="sort" data-sort="university">University</th><th class="sort" data-sort="no">Billionaires</th><th class="sort" data-sort="no2">Billionaires Rank</th><th class="sort" data-sort="rank">U.S. News Rank</th></thead><tbody class="list"></tbody></table>');
$.each(tabletop.sheets("Sheet1").all(), function(i, cat){
var htmltable = $('<tr><td class="university">' + cat.university + '</td>');
htmltable.append('<td class="no">' + cat.numberofbillionaires + '</td>');
htmltable.append('<td class="no2">' + cat.rankedbybillionaires + '</td>');
htmltable.append('<td class="rank">' + cat.usnewsranking + '</td></tr>');
htmltable.appendTo("tbody");
})
}
</script>
<script type="text/javascript" src="options.js"></script>
</html>
JS file
var options = {
valueNames: [ 'university', 'no' , 'no2' , 'rank']
};
var userList = new List('tablesetter', options);
The problem
var userList = new List('tablesetter', options); should be executed when the dom has an element of the list class; since in the question's code the list class default to list" , so such element should be <tbody class="list"> that is going to be appended to the #tablesetter only when the showInfo function receive data from google.
The solution
We ensure that the var userList = new List('tablesetter', options) statement executes after ( ie: at the end ) of the showInfo function; in other words move var userList = new List('tablesetter', options); from options.js just before the closing right bracket of the showinfo function.
More details
in the question's code when list.js tries to init() the dom is:
and list.list is still undefined when list.js defines it's getItemSource() functions:
with the proposed fix, at the var userList = new List('tablesetter', options); the dom is like:
and when defines it's getItemSource() functions the list.list can use the tbody as aspected:
If you look at this post, I'm sure your just missing some of the minimum requirements for list.js to function properly. Try to dynamically add the input with id and class of "search" as well with your other classes. Let me know if this helps.
https://stackoverflow.com/a/23078200/4812515