Dynamic Dropdown from Mongo - javascript

I have a mongoDB with a DB = Staff and a collection = records. It contains a list of employees, and one of the fields is workgroup and it has items like "management", "union", "support staff", etc.
I want to populate a dropdown list with the values of the workgroup field and then use it to retrieve all records from the specified value selected in the dropdown.
I am using Ruby and I can retrieve the values ok (I can see them in the console), but they do not populate the dropdown list.
This is my Ruby statement:
get '/workgroup' do
Record.all.to_a.collect(&:workgroup).uniq.to_json
end
My attempt at the javascript is:
<script>
//var json = 'http://localhost:4567/api/v1/workgroup';
$(document).ready(function()
{
$.getJSON("/api/v1/workgroup",function(obj)
{
$.each(json.records,function(key,value)
{
var option = $('<option />').val(value.workgroup);
$("#dropDownDest").append(option);
})
})
});
</script>
Once I get the information in the dropdown, I want to use it to return all records with that workgroup value to a table. I haven't figured that part out yet. One step at a time!
Thanks!!

Within your $.getJSON call back you are referencing json.records, but there is no json variable or object.
The argument you are passing to the callback is obj. I think you really want to be doing $.each(obj, function(key, value)...

Related

How to save results from dynamic cascading drop down list?

I have 2 cascading drop down list , when page loads, data is loaded to the 1st DDL, when item is selected from this list its goes to the database and fetch matching items and populate 2nd DDL. I want to prevent going twice to the DB on selection.
For example, I am loading 1st DDL with cars manufactures then click on Toyota what happens next is it goes to DB and fetches all Toyota's models and populates the 2nd DDL, after that i select different car manufacture, same thing happens. Now when i select again Toyota from the 1st list it will not go to DB, it will pull the data from previous request.
I will like to keep an object (like dictionary) of the requests, so if item is already been requested it will not go back to the DB but use local saved data.
You can store list return from server through LocalStorage in Javascript. By using setItem()function as shown below.
window.localStorage.setItem('Toyota', 'Models');
Where Toyota is the key and Models is the value. Also note that LocalStorage can only store strings.
To store arrays or objects you would have to convert them to strings.
To do this we use the JSON.stringify() method before passing to setItem() .
const models = {
1: "Model-1",
2: "Model-2",
}
window.localStorage.setItem('Toyota', JSON.stringify(models));
Now when ever you select different car manufacture check its value in LocalStorage object first.
It accepts only one parameter which is the key and returns the value as a string.
To retrieve the Toyota key stored above:
window.localStorage.getItem('Toyota');
This returns a string with value as.
“{“1”:”Model-1”,”2”:”Model-2”}”
To use this value, you would have convert it back to an object.
To do this, we make use of JSON.parse() method which converts a JSON string into a Javascript Object.
JSON.parse(window.localStorage.getItem('Toyota'));
Please keep in mind to check weather your browser support Local storage or not.
if (typeof(Storage) !== "undefined") {
// Code for localStorage
} else {
// No web storage Support.
}
You can use Map() object to store the data based on key.
Find more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
var brandModelsList = new Map();
function getBrandModels(brand)
{
if(brandModelsList.has(brand))
{
modelList = JSON.parse(brandModelsList.get(brand));
// Do stuff with second dropdown
}
//Your ajax stuff to get data
$.ajax({
url: 'server url',
data: {name: brand},
dataType: 'json',
}).done(response => {
brandModelsList.set(brand, JSON.stringify(response));
// Do stuff with second dropdown
});
}
It has support in most of modern browsers. A best tutorial on this is https://javascript.info/map-set-weakmap-weakset.
you can do this via JavaScript as #Rahat Hameed stated if the cascading dropdown values are not changed frequently, if they can be changed e.g (you can updated them via some logic).Then preferable ways it to fetch them from database.

Filter a SharePoint list via dynamic checkboxes instantly (with C# and/or Ajax)

I'm currently looking for a way to add a filter function to a list in SharePoint, which filters the lists content via checkbox selection.
This little mockup might help to understand what I'm talking about:
The idea is to have a normal SharePoint custom list on the right and a checkboxlist on the left side, which will be generated dynamically from the content of the list -> One column is a "filter group" and all the field contents are the filter values.
When selecting one or multiple values on the left side, the items in the list should instantly be filtered accordingly (ajax, without reloading the page).
For example in the mockup, selecting "New York" and "Blue" would only show the item "Steve's Car".
You now, like a product filter in almost every online shop and so on.
How can that be achieved? Would be awesome if this could be included in my solution package (which includes other stuff in C#/jQuery already).
I'm new to frontend customization in SharePoint, but I'm sure there's a way :-)
Edit: I'm using SP2016 by the way.
Pandora!
As i understand it, your first question is how you can dinamically get values for left side filter. I see there two ways: first way, you can build caml query and get items from list; second way, you can use ctx.ListData, which sharepoint initialize by itself and in ctx.ListData.Row (array of items) process items and get unique field values. Note, that ctx.ListData.Row contains only items loaded in list view on the page.
For list filtration you can concat filter link for hash of the page. Example: "?List={ListID}&View={ViewID}&FilterField1=Color-FilterValue1=Blue". Try to filter columns on list and you will see url modification. ListID and ViewId you can retrieve by ctx.listName and ctx.view.
And then pass it in function MyRefreshPageToEx. List will be filtered.
More list filtration info
function FilterList(){
var tableId = $(".ms-listviewtable").attr("id");
var filterUrl = "?List={ListID}&View={ViewID}&FilterField1=Color-FilterValue1=Blue";
MyRefreshPageToEx(tableId, filterUrl, false);
}
function MyRefreshPageToEx(lvTableID, url, bForceSubmit) {
var tblv = document.getElementById(lvTableID);
var clvp = CLVPFromCtx(tblv);
if (clvp != null && clvp.ctx.IsClientRendering) {
clvp.RefreshPaging(url);
clvp.ctx.queryString = url;
if ((typeof clvp.ctx.operationType == "undefined" || clvp.ctx.operationType == SPListOperationType.Default) && Boolean(clvp.ctx.ListData)) {
var fromPage = clvp.ctx.ListData.FirstRow - 1;
var toPage = Number(GetUrlKeyValue("PageFirstRow", false, url));
if (!isNaN(fromPage) && !isNaN(toPage) && fromPage != toPage)
fromPage < toPage ? (clvp.ctx.operationType = SPListOperationType.PagingRight) : (clvp.ctx.operationType = SPListOperationType.PagingLeft);
}
}
else {
SubmitFormPost(url, bForceSubmit);
}
}

How to assign a variable using firebase javascript

Reading the firebase doc this line:
database.ref('/').once('value').then(function(snapshot)
That is from a paragraph titled "Read data once" which I'm assuming reads in all the data from the database.
I'm just struggling to figure out how to assign data from the object that is returned to a variable in javascript.
What I want to do is populate a dropdown list with place names.
For instance if I have a field called Location in the db containing place names eg Sydney, Melbourne, Brisbane how would I get the data from the returned object and assign it a variable called place so I can then use the place variable to populate the html dropdown list.
You can try with this simple code -
database.ref('/').once('value').then(function(snapshot){
var list = snapshot.val();
if(list)
{
for (item in list)
{
itemIndex = item;
item = list[item];
//access your properties of the object say - item.location
}
}
});
You have to user 'child_added'
example:
var dbRef = firebase.database().ref().child('someChild');
dbRef.on('child_added', function(snap){
var res = snap.val().theValueYouNeed;
});
The code above gets the specific child in your db like this:
someChild:{
theValueYouNeed:"some value"
}
Then you can populate your list with the values.
I hope this helps!

How to assign element values inside jquery.each() function

I have a php page which calls a javascript function to populate it.
The page is a list of users each with their own form, the form id has the id appended to its name to allow edit, delete etc on each user.
The form is is the shape of an html page that is in theory sucked in for each record.
I am using jquery each() to iterate over the records, then in theory the html page should be sucked in and populated for each record. I have tried for loop also.
The code below produces the correct number of forms but empty.
Other efforts have left me with only the last record populating the fist box and the others empty.
Any help greatly appreciated.
$(Udata).each(function(uId, value){
uid = value.uid;
var uname = value.uname;
function setValues() {
window.document.getElementById("username").value=uname;
window.document.getElementById("frmDelUsr").setAttribute("name","frmDelUsr"+uid);
}
$.get("users.html",{}, function (data) {
$("#divfrmDelUser").append(data), function(){setValues();}
});
$(Udata).each(function(uId, value){
uid = value.uid;
var uname = value.uname;
function setValues() {
window.document.getElementById("username").value=uname;
window.document.getElementById("frmDelUsr").setAttribute("name","frmDelUsr"+uid);
}
$.get("users.html",{}, function (data) {
$(this).children('.divfrmDelUser').append(data), function(){setValues();} //<--- CHANGED
});
First you'd have to change the element with the ID "divfrmDelUser" by making that ID into a class(just erase "id" and type "class" obviously), then what this ought to do is select the current Udata being used, and then look for the elements within it containing the class "divfrmDelUser" and do what you set it to do past that.

How do I place data from http json in a new scope variable [angularJS]

I wrote an $http.get function to extract data stored in a database.
I would like to use the database data in a dropdown function in AngularJS. Now this means that I have to create a new $scope JSON data variable and store the actual database data in it just so I can access it in my HTML page.
<select popover="Choose your input drug, type to filter list of drugs" data-ng-model="currentData"
data-ng-options="name for name in ourDataName" style="width:300px;" convert-to-number >
</select>
ourDataName in data-ng-options is the variable I defined inside the controller as $scope.ourDataName, and it is supposed to have all the drug names inside it. It is possible for me to do what is written inside the get function below; however, the problem is that there are over 100 drug names:
$http.get(URL).success(function (data) { //Note URL is where I stored my database. I did not put it for privacy reasons
$scope.ourDataName =
[
data[1].drug_name,
data[2].drug_name,
data[3].drug_name
]
});
I tried to put a for loop over the JSON data as such:
for(var i=0; i<100;i++)
{
$scope.ourDataName =
[
data[i].drug_name
]
}
The problem is it ended up showing the 100th drug name only since it shows what the loop ends at.
I am out of solutions. Is there any way to loop through the database and store them in a new variable without having to go over each as I did at first?
You don't need to create another data set for dropdown.
Use data directly which http get return.
Try like this
Controller
$http.get(URL).success(function (data) { //Note URL is where I stored my database. I did not put it for privacy reasons
$scope.ourDataName=data;
});
View
<select popover="Choose your input drug, type to filter list of drugs" data-ng-model="currentData"
data-ng-options="name.drug_name for name in ourDataName" style="width:300px;" convert-to-number >
</select>
Anik's answer is great. But if you want to go with a loop option, you can use the below code in your controller.
$scope.ourDataName = [];
$http.get(URL).success(function (data) {
angular.forEach(data, function(drug) {
$scope.ourDataName.push(drug.drug_name);
});
});

Categories

Resources