Im using JQuerys Autocomplete plugin, but it doesn't autocomplete upon entering anything.
Any ideas why it doesnt work? The basic example works, but not mine.
var ppl = {"ppl":[{"name":"peterpeter", "work":"student"},
{"name":"piotr","work":"student"}]};
var options = {
matchContains: true, // So we can search inside string too
minChars: 2, // this sets autocomplete to begin from X characters
dataType: 'json',
parse: function(data) {
var parsed = [];
data = data.ppl;
for (var i = 0; i < data.length; i++) {
parsed[parsed.length] = {
data: data[i], // the entire JSON entry
value: data[i].name, // the default display value
result: data[i].name // to populate the input element
};
}
return parsed;
},
// To format the data returned by the autocompleter for display
formatItem: function(item) {
return item.name;
}
};
$('#inputplace').autocomplete(ppl, options);
Ok. Updated:
<input type="text" id="inputplace" />
So, when entering for example "peter" in the input field. No autocomplete suggestions appear. It should give "peterpeter" but nothing happens.
And one more thing. Using this example works perfectly.
var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
$("#inputplace").autocomplete(data);
Well, looking at the code in that plugin, the "parse" option looks like it's only called when the data is retrieved by an AJAX call. As an experiment, you might try passing in the data such that you don't need it:
var ppl = [{"name":"peterpeter", "work":"student"},
{"name":"piotr","work":"student"}];
Related
I am a little surprised I am not finding anything out there on this. My question is really 2 parts:
Is it possible to generate a form select field (preferably with Autoform) with all of the options being registered users emails or names? If so could anyone please provide an example?
Is it possible (again autoform is preferred) to have conditional form field rules. EX: I have a client with multiple locations. One select would be for the client, and depending on what is selected here would populate another select that generates all of this clients locations. Again ANY examples would be appreciated!
Thanks so much!
Really not answering but rather just giving a better visual of the code I added. I am getting an input box but not a select box. There is nothing inside the input. Here is what I added:
inspector: {
type: String,
autoform: {
type: "selectize",
options: function() {
return Meteor.users.find({}, fields: {
emails: 1,
profile: 1
}).map(function(c) {
var optionsArray = [];
for (var i = 0; i < c.length; i++) {
optionsArray[i] = {};
optionsArray[i].label = c[name][i];
optionsArray[i].value = c[name][i];
}
return optionsArray;
})[0];
},
defaultValue: function() {
return "Choose a User";
},
}
},
Just curious what I got wrong.
Autoform is awesome work done by aldeed. So much of functionality inside it, it would take some time to read and understand the documentation. I will try to help with an example.
Is it possible to generate a form select field (preferably with Autoform) with all of the options being registered users emails or names? If so could anyone please provide an example?
var myAutoForm = new SimpleSchema({
"formSelectField": {
type: String,
autoform: {
type: "selectize",
options: function() {
return collectionName.find({ criteria to get the registered user names }).map(function(c) {
var optionsArray = [];
for (var i = 0; i < c.length; i++) {
optionsArray[i] = {}; // creates a new object
optionsArray[i].label = c[name][i];
optionsArray[i].value = c[name][i];
}
return optionsArray;
})[0];
},
defaultValue: function() {
return the default value to be picked on the select dropdown
},
}
},
});
Is it possible (again autoform is preferred) to have conditional form field rules. EX: I have a client with multiple locations. One select would be for the client, and depending on what is selected here would populate another select that generates all of this clients locations. Again ANY examples would be appreciated!
For this, I will put only the options part of the autoform
options: function() {
if(AutoForm.getFieldValue('fieldName', 'formId')==='something')
})
return someValue;
},
I am trying to discern the index # of the pattern selected in the Combo-box. I need to pass this index value in order for another function to read from a file at the correct location. Essentially, selecting the a pattern in the combobox will let me do a lookup for specifications associated with the selected pattern based on the index. To the best of my knowledge the Vaadin Combobox does not have an index associated with the combobox items, but you are able to pass a different value than the displayed label: https://vaadin.com/docs/-/part/elements/vaadin-combo-box/vaadin-combo-box-basic.html (see: Using Objects as Items). This is solution I am trying to implement, however it gets tricky because I am dynamically populating the combobox items from a JSON file.
The code to dynamically populate the items:
paver = document.querySelector('#paver');
//alert('script executed');
patterns = [];
familyind=y;
$.getJSON('menu.json').done(function(data){
//alert('getJSON request succeeded!');
family = (data.gui[x].family[y].display);
for(ind = 0; ind < data.gui[x].family[y].pattern.length; ind++){
var patternLbl = data.gui[x].family[y].pattern[ind].name;
var patternObj = '{ pattern: { label: "' + patternLbl + '", value: ' + ind + ' } }';
patterns[ind] = patternObj;
}
document.getElementById("cb1").items=patterns;
})
.fail(function(jqXHR, textStatus, errorThrown)
{
alert('getJSON request failed! ' + textStatus);
})
.always(function() { }};
HTML for the ComboBox
<div id="patternSelect">
<template is="dom-bind" id="paver">
<div class="fieldset">
class="patterns" items="[[patterns]]" item-label-path="pattern.label" item-value-path="pattern.value"></vaadin-combo-box>
</div>
</template>
</div>
The output I get when I try to execute this is that the entire constructed string gets assembled into my selection choices. Theoretically, this should not have happened because the item-value-path and item-label-path were specified when declaring the combobox.
Screenshot of Output
It says: { pattern: { label: "A-3 Piece Random", value: 0 } }
WORKING TOWARDS A SOLUTION SECTION:
___________(April 27, 7:00pm)___________
Suggested solution to use,
var patternObj = { pattern: { label: patternLbl, value: ind } };
works fine in displaying labels:
However, I am using a trigger to detect when the value in the combo-box is changed and return the new value. Here is the code for the trigger:
// select template
var paver = document.querySelector('#paver');
// define the ready function callback
paver.ready = function () {
// use the async method to make sure you can access parent/siblings
this.async(function() {
// access sibling or parent elements here
var combobox = document.querySelector('#cb1')
combobox.addEventListener('value-changed', function(event) {
// FOR REFERENCE LOG ERRORS, THIS COMMENT IS ON HTML:215
console.log(event.detail.value);
patval = event.detail.value;
console.log(patval)
// Do stuff with fetched value
});
});
};
I have made the suggested change to using a 'value-changed' trigger. It works very well with two slight issues. First, it returns each of the console log calls twice (not sure why twice). Second, when I select the first combo-box item it returns my values but does not set the label as selected. This is not an issue with the other combo-box items, but the first item needs to be selected twice to have the label set. Please watch this short video for a demonstration: https://youtu.be/yIFc9SiSOUM. This graphical glitch would confuse the user as they would think they did not select a pattern when they know they had. Looking for a solution to make sure the label is set when the first item is selected.
You are setting a currently a String to patternObj while you should be setting an Object.
Try using either var patternObj = JSON.parse('{ pattern: { label: "' + patternLbl + '", value: ' + ind + ' } }'; or even simpler:
var patternObj = { pattern: { label: patternLbl, value: ind } };
Also, I would recommend initializing the patterns = [] inside the done callback to make sure you're not leaving any old items in the patterns when the data changes.
I have handsontable and I want to get data enter on handsontable cell into server side. I have tried to ran below code but data is not in expected format. I was expecting to get the data in pure json format as column header as key.
Html code
<div class="handsontable" id="example"></div>
<input type="button" name="submit" value="submit" onclick="submitForm()" />
code for creating the handsontable
$(document).ready(function () {
$('#example').handsontable({
startRows: 2,
startCols: 2,
rowHeaders: true,
colHeaders: true,
contextMenu: true,
});
});
code for extracting the information from handsontable
function submitForm(){
var $container = $('#example');
var htContents = JSON.stringify($container.handsontable('getData'));
alert(htContents);
}
Currently handsontable has 2 rows and 2 column. Now if I press the button with cell value (1,1)=11,(1,2)=12,(2,1)=21 and (2,2)=22, result I am getting is in alert window
[["11","12"],["21","22"]]
But result I am expecting is
[{"A":"11","B":"12"},{"A":"21","B":"22"}]
where A and B is column header.
For others who didn't discover the answer immediately, see #hakuna1811's comment above that since version 0.20.0 of Handsontable the .getSourceData() call should be used instead if you want to get your data back in the same format as you provided it - for example as an array of objects. It is not clear why the .getData() call's behavior was modified and it is not explained in the related GitHub issue noted in #hakuna1811's comment, but at least we have a working solution - thanks again to #hakuna1811 for the answer - it saved a lot of hunting around!
That's great that you're expecting that, but that's just not how that function works :P
Here's what you actually want:
For starters, you don't show us where you set the data option. If you look at this fiddle, I use the different notation to generate a Handsontable object which allows me to specify the format of data.
If data is given how I show it, as an array of row Objects, where each Object is in the format you describe, then the hot1.getData() method returns what you expect.
As it stands, I have no idea what data format you're using so either adopt this way of instantiating HOT or show us how you're doing it.
Good luck!
You need mapping the result. let's assume htContents is variable which contains [["11","12"],["21","22"]]
function buildObject(data) {
return {
'A': data[0],
'B': data[1]
};
}
var newResult = htContents.map(buildObject); // newResult must be expected data
The getSourceData() method returns the desired format, but will not reflect the correct row and column order as seen on screen. The following typescript code works for me:
protected getVisualTableData(): object[] {
const tableData = [];
for (let i = 0; i < this.hot.countRows(); i++) {
tableData.push(this.visualObjectRow(i));
}
return tableData;
}
protected visualObjectRow(row: number): object {
const obj = {};
for (let i = 0; i < this.hot.countCols(); i++) {
obj[this.hot.colToProp(i)] = this.hot.getDataAtCell(row, i);
}
return obj;
}
I'm trying to set up a cascading dropdown using JSON data. I have it working somewhat but need some assistance getting the 2nd tier to work as intended. Currently it seems to be grabbing the number in the array.
Ideally for my 2nd tier I want to show the text in the dropdown as the option text, and I'd like to use the id field in the json as the value of the option.
var data = {
"Crime":[
{"id":"1","text":"Number of police"},
{ "id":"2","text":"Number of crimes"}
],
"Health":[
{"id":"3","text":"Number of doctors"},
{"id":"4","text":"Number of hospital visits"},
{"id":"5","text":"Number of nurses"}
],
}
I have a jsfiddle showing what I have so far.
Happy to use whatever combination of javascript/jquery works best.
The way you have used for..in seems to be incorrect. The question variable will not contain the entire value if the pointed collection (data[this.value], in this case) is not a simple array. Rather, it would contain the index of the first row, the second row and so on. I request you to read this for a more in-depth understanding :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
This line here
questionSel.options[questionSel.options.length] = new Option(question, question);
Must read this way
questionSel.options[questionSel.options.length] = new Option(
data[this.value][question].text,
data[this.value][question].id);
Here's an updated fiddle after this change has been made:
http://jsfiddle.net/tc1f3kup/2/
please try this
var data = {
"Crime":[
{"id":"1","text":"Number of police"},
{ "id":"2","text":"Number of crimes"}
],
"Health":[
{"id":"3","text":"Number of doctors"},
{"id":"4","text":"Number of hospital visits"},
{"id":"5","text":"Number of nurses"}
],
}
window.onload = function () {
var themeSel = document.getElementById("theme"),
questionSel = document.getElementById("questions");
for (var theme in data) {
themeSel.options[themeSel.options.length] = new Option(theme, theme);
}
themeSel.onchange = function () {
questionSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for(var i=0;i<data[this.value].length;i++)
{
questionSel.options[questionSel.options.length] = new Option(data[this.value][i].text, data[this.value][i].id);
}
}
}
working fiddle
http://jsfiddle.net/tc1f3kup/3/
I attempting to pull data from a JSON file. I cannot change the way the data is keyed or labeled in the file since it is being converted from a CSV file.
My JSON data looks like this (I am using a grep filter and then storing it in a variable but for brevity I am not showing that part unless someone needs to see it):
var medicare = {
"": "",
"80101": "NC",
"80104": "NC",
"80152": "24.61",
"80154": "22.72",
"80299": "18.83",
"82055": "14.85",
"82145": "9.71",
"82542": "16.01",
"82646": "23.91",
"82649": "23.91",
"83805": "24.23",
"83840": "13.04",
"83887": "22.26",
"83925": "26.74",
"83992": "20.20",
"99080": "NC",
"99358": "NC",
"Carrier Type": "Medicare",
"G0434": "12.17",
"State": "Minnesota",
"id": 122
}
I have managed to load the file using $.getJSON() and I have also managed to make a filter using $.grep() to filter arrays by State and Carrier Type. Now I need to create a function that will be able to return the value of any of the given keys.
function findInside( array, key ) {
return array[key]; // <-- This is my problem.
}
Which I can use to return value by running:
console.log(findInside(medicare, "80101"))
I just need to be able to get the value. I don't think I need to do any loops and such. I'm still new to JavaScript and am banging my head over this one, and it should be pretty easy.
Thanks in advance!
EDIT: Here is all the relevant code code except the JSON file. I wish I wasn't using window.numbers the way I am but I being so new to this, I didn't know any other way to make it work.
jQuery(document).ready(function($) {
// First things first, fill the state picker.
$.each(usStates, function(i, option) {
$('#state').append($('<option/>').attr("value", option.abbreviation).text(option.name));
});
// Next we need to load in the JSON Data file.
$.getJSON('data.json', function(data) {
window.numbers = data
});
$("#state").change(function(){
//Lets get the stuff in the fields.
state = $("#state").val();
stateName = $("#state option:selected").text();
//Filter all through all the data.
var workersComp = filterData("Worker's Comp", stateName);
var commercial = filterData("Commercial", stateName);
var medicare = filterData("Medicare", stateName);
var medicaid = filterData("Medicaid", stateName);
console.log(medicare);
console.log(findInside(medicare, "80101")); // undefined
});
})
//Functions
function filterData( i, d) {
var r = $.grep( window.numbers, function(val, index) {
return val.State === d;
});
var output = $.grep(r, function(val, index) {
return val["Carrier Type"] === i;
});
return output
}
function findInside( array, key ) {
return array[key];
}
jQuery's .grep() method returns an array of answers.
Your logic here that filters the data is receiving an array of results back. If you are guaranteed to have one and only one of each item, the short fix is to change:
//Filter all through all the data.
var workersComp = filterData("Worker's Comp", stateName);
var commercial = filterData("Commercial", stateName);
var medicare = filterData("Medicare", stateName);
var medicaid = filterData("Medicaid", stateName);
To this (gets the first element in the resulting array for each type):
//Filter all through all the data.
var workersComp = filterData("Worker's Comp", stateName)[0];
var commercial = filterData("Commercial", stateName)[0];
var medicare = filterData("Medicare", stateName)[0];
var medicaid = filterData("Medicaid", stateName)[0];
The longer term fix is to revisit your filtering logic a bit and see if you can come up with a better pattern.
For Example: If you could work your data into a form that looks something like:
var states = {
…,
"Minnesota": {
"Worker's Comp": {…},
"Commercial": {…},
"Medicare": {
"80101": "NC",
"80104": "NC",
"80152": "24.61",
...
},
"Medicaid": {…}
},
...
}
Selecting the right value could be simplified to:
states[stateName]["Medicare"]["80101"]