How to represent form options that depend on other forms - javascript

I have a form that is suposed to help to user to choose a specific thing at the end, but as the user fills the first options, the others below change. Something like this:
Type:
{
t1:{
Number of X:{
1:{...}
2:{...}
}
Number of Y:{...}
}
t2:{
Number of X:{
100:{...}
200:{...}
}
Number of Y:{...}
}
}
The user has the field Type with the options t1 and t2, when they choose t1, the field "Number of X" will be filled with 1 and 2, if they choose t2, the field "Number of X" will be filled with 100 and 200, and so on. Some of the choices depend on more than one field, its not straight down dependency (something like, if the user chooses "Number of X" = 100 then Foo is "A", else, Foo can be "A", "B" or "C", but Foo is not bellow "Number of X").
I tried a really naive implementation where I would set up event listeners on every field and see their changes, but eventually the code started growing out of control and I have a bunch of $("#foo").change(function(){...}); and its not imediatly obvious that the field listening to this is bar and not fbar.
I also tried JSON (as the example above), but there's a lot of repetition, the deeper the tree grows and the number of possibilites increase, I have to write the same fields again and again. Sometimes choosing t1 will change an option directly even though its not directly bellow it, and even though it usually depends on another field entirely, and that's more repetition in JSON.
How do I approach this problem? Is there a readable solution? Too much code is not the problem, as long as one can look at the code and understand the dependencies and their effects.
A code example (kinda like my code right now):
HTML:
<select id="type">
<option value=1>a</option>
<option value=2>b</option>
</select>
<select id="numOfX">
</select>
<select id="numOfY">
</select>
js:
$("#type").change(function()
{
if($("#type").val() == 1)
{
$("#numOfX").append(new Option(1, "1", false, false));
$("#numOfX").append(new Option(2, "2", false, false));
}
else if($("#type").val() == 2)
{
$("#numOfX").append(new Option(1, "100", false, false));
$("#numOfX").append(new Option(2, "200", false, false));
}
});
$("#numOfX").change(function()
{
...
});

Update - Add example
Have you try backbone.js library? It will make the Javascript code more manageable by adding models & structures. There is a learning curve though but it is really great. Once you learn Backbone, you can make use of the Backbone Forms plugin which will help in the dropdown management. Below is the demo link & sample code:
Example 1
$(function() {
var cities = {
'UK': ['London', 'Manchester', 'Brighton', 'Bristol'],
'USA': ['London', 'Los Angeles', 'Austin', 'New York']
};
var subAreas = {
'London' : ['L1', 'L2', 'L3', 'L4'],
'Manchester' : ['M1', 'M2', 'M3', 'M4'],
'Brighton' : ['B1', 'B2', 'B3', 'B4'],
'Bristol' : ['BR1', 'BR2', 'BR3', 'BR4'],
'Los Angeles' : ['LA1', 'LA2', 'LA3', 'LA4'],
'Austin' : ['A1', 'A2', 'A3', 'A4'],
'New York' : ['NY1', 'NY2', 'NY3', 'NY4']
};
//The form
var form = new Backbone.Form({
schema: {
country: { type: 'Select', options: ['UK', 'USA'] },
city: { type: 'Select', options: cities.UK },
subArea: { type: 'Select', options: subAreas[cities.UK[0] ] }
}
}).render();
form.on('country:change', function(form, countryEditor) {
var country = countryEditor.getValue(),
newOptions = cities[country];
form.fields.city.editor.setOptions(newOptions);
var city = newOptions[0],
areaOptions = subAreas[city];
form.fields.subArea.editor.setOptions(areaOptions);
});
form.on('city:change', function(form, cityEditor) {
var city = cityEditor.getValue(),
newOptions = subAreas[city];
form.fields.subArea.editor.setOptions(newOptions);
});
//Add it to the page
$('body').append(form.el);
});​
Example 2
$(function() {
var cities = {
'UK': ['London', 'Manchester', 'Brighton', 'Bristol'],
'USA': ['London', 'Los Angeles', 'Austin', 'New York']
};
var subAreas = {
'UK.London' : ['L1', 'L2'],
'USA.London' : ['L3', 'L4'],
'UK.Manchester' : ['M1', 'M2', 'M3', 'M4'],
'UK.Brighton' : ['B1', 'B2', 'B3', 'B4'],
'UK.Bristol' : ['BR1', 'BR2', 'BR3', 'BR4'],
'USA.Los Angeles' : ['LA1', 'LA2', 'LA3', 'LA4'],
'USA.Austin' : ['A1', 'A2', 'A3', 'A4'],
'USA.New York' : ['NY1', 'NY2', 'NY3', 'NY4']
};
var hashFunc = function(country, city){
return country + "." + city;
};
//The form
var form = new Backbone.Form({
schema: {
country: { type: 'Select', options: ['UK', 'USA'] },
city: { type: 'Select', options: cities.UK },
subArea: { type: 'Select', options: subAreas[ 'UK.London' ] }
}
}).render();
form.on('country:change', function(form, countryEditor) {
var country = countryEditor.getValue(),
newOptions = cities[country];
form.fields.city.editor.setOptions(newOptions);
var city = newOptions[0],
areaOptions = subAreas[hashFunc(country, city) ];
form.fields.subArea.editor.setOptions(areaOptions);
});
form.on('city:change', function(form, cityEditor) {
var city = cityEditor.getValue(),
newOptions = subAreas[hashFunc(form.getValue().country, city)];
form.fields.subArea.editor.setOptions(newOptions);
});
//Add it to the page
$('body').append(form.el);
});​
As you also develop for mobile (probably Phonegap), you can also try ZeptoJS as an alternative for jQuery. It will improve the speed alot.

The task outlined is complex because of dependencies, so you must think of the ways to define your dependencies. Here is one way I would do it:
Define models which handle data.
Define dependencies.
Manage dependencies.
Below you can see a conceptual model how I see this all implemented (at the end of my answer I describe things which are not provided in this pseudo code):
//data/model structure for Type.
var type = {
//list all values.
values: [
{ id: 1, text: 't1', visible: true },
{ Id: 2, text: 't2', visible: true }
],
//evaluates visibility of item using dependencies.
//depends on nothing, so takes no arguments except item.
evaluate: function(item) {
return; //depends on nothing.
},
// this event fires when selected item changes.
onChange: event
};
//data/model structure for number of X.
var numberOfX = {
//list all values.
values: [
{ id: 1, text: '1', visible: true },
{ id: 2, text: '2', visible: true },
{ id: 3, text: '100', visible: true },
{ id: 4, text: '200', visible: true }
],
//evaluates visibility of item using dependencies.
//since numberOfX depends on Type, it takes type as second argument.
//it would take more arguments if it depended on other things too.
evaluate: function(item, type) {
// next line will fire onChange event.
item.visible =
( [1,2].indexOf(item.id) >=0 && type.id == 1 ) ||
( [3,4].indexOf(item.id) >=0 && type.id == 2 );
},
// this event fires when selected item changes.
onChange: event
};
//data/model structure for number of Y.
var numberOfY = { /* omitted. This is similar to the previous ones */ }
//numberOfX depends on Type.
//if it depended on more objects, then we would pass them as additional arguments.
register_dependency(numberOfX, type);
//numberOfY depends on Type.
register_dependency(numberOfY, type);
//... etc: define other dependencies.
Event mechanism is not there in JavaScript, but implementing one is not hard. You can use some framework for that as well.
register_dependency function builds a graph of dependencies simply by registering for events, as described below (managing dependencies):
When onChange event fires on any model, evaluate is called for each item in the dependency tree. For example, when type.onChange fires, we have numberOfX and numberOfY objects. Their values array is enumerated in loop and evaluate is called for each item (passing item and type as arguments).
Conclusion: although this code seems complex, still it's more self-descriptive and allows to have graph of dependencies between multiple objects on the page. Also, all the complexity lays on the toolkit/framework level, which could be easily re-used when implemented only once.
EDIT: Forgot to outline that you would need to have some mechanism to bind to this kind of model and show it on the page, which is also trivial. For example, have a look at knockout.js.

Related

Why javascript array sort doesn't compare all elements with each other?

I'm trying to understand why Javascript array sort doesn't work with the following logic. I have no problems making my own algorithm to sort this array, but I'm trying to make it with the Javascript sort built-in method to understand it better.
In this code, I want to push entities that "belongs to" another entity to the bottom, so entities that "has" other entities appear on the top. But apparently, the sort method doesn't compare all elements with each other, so the logic doesn't work properly.
Am I doing something wrong, or it is the correct behavior for the Javascript sort method?
The code I'm trying to execute:
let entities = [
{
name: 'Permission2',
belongsTo: ['Role']
},
{
name: 'Another',
belongsTo: ['User']
},
{
name: 'User',
belongsTo: ['Role', 'Permission2']
},
{
name: 'Teste',
belongsTo: ['User']
},
{
name: 'Role',
belongsTo: ['Other']
},
{
name: 'Other',
belongsTo: []
},
{
name: 'Permission',
belongsTo: ['Role']
},
{
name: 'Test',
belongsTo: []
},
]
// Order needs to be Permission,
let sorted = entities.sort((first, second) => {
let firstBelongsToSecond = first.belongsTo.includes(second.name),
secondBelongsToFirst = second.belongsTo.includes(first.name)
if(firstBelongsToSecond) return 1
if(secondBelongsToFirst) return -1
return 0
})
console.log(sorted.map(item => item.name))
As you can see, "Role" needs to appear before "User", "Other" before "Role", etc, but it doesn't work.
Thanks for your help! Cheers
You're running into literally how sorting is supposed to work: sort compares two elements at a time, so let's just take some (virtual) pen and paper and write out what your code is supposed to do.
If we use the simplest array with just User and Role, things work fine, so let's reduce your entities to a three element array that doesn't do what you thought it was supposed to do:
let entities = [
{
name: 'User',
belongsTo: ['Role', 'Permission2']
},
{
name: 'Test',
belongsTo: []
},
{
name: 'Role',
belongsTo: ['Other']
}
]
This will yield {User, Test, Role} when sorted, because it should... so let's see why it should:
pick elements [0] and [1] from [user, test, role] for comparison
compare(user, test)
user does not belong to test
test does not belong to user
per your code: return 0, i.e. don't change the ordering
we slide the compare window over to [1] and [2]
compare(test, role)
test does not belong to role
role does not belong to test
per your code: return 0, i.e. don't change the ordering
we slide the compare window over to [2] and [3]
there is no [3], we're done
The sorted result is {user, test, role}, because nothing got reordered
So the "bug" is thinking that sort compares everything-to-everything: as User and Role are not adjacent elements, they will never get compared to each other. Only adjacent elements get compared.

Interaction with gridData on ui-grid edit events

I am using Angular ui-grid and am pretty new at it. I receive an array of objects to render data for each row. Each object, hence each row , has a field change:false which marks whether any field on that row has been edited or not. I have kept this field visible : false on screen.
However, whenever any change is made to any column of any row, I want to set this field as change:true.
How can this be achieved on the change of a ui-dropdown field or any other field for that matter.
I have this as my changing column:
{ name: "carrier_influence_group", displayName: "Carrier influence group", enableCellEdit: true,
editableCellTemplate: 'ui-grid/dropdownEditor', type:'object', cellFilter: 'cigFilter', editDropdownValueLabel: 'name',
editDropownOptionsArray: [{ id: 10, name: 'Small' }, { id: 11, name: 'Medium' }, { id: 12, name: 'Large' }]
},
I tried looking for any options available. But couldn't find any way in official docs. Kindly suggest a way or some relevant links
You can use the afterCellEdit event for this.
$scope.gridOptions.onRegisterApi = function (gridApi) {
$scope.gridApi = gridApi;
gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
if (newValue !== oldValue) {
rowEntity['change'] = true;
}
});
});

How to select an option in a dropdown list angularjs

I am using AngularJS directive and I need to set a selected option of a dropdown list in my template.
<select id="energySource" ng-options="o.name for o in energyOptions" ng-model="energy" ng-selected="energy" ng-change="energyChange();"></select>
The content of the optionlist depends on resources send by a server when the page is loaded.
var energyChosen = "All";
angular.element(document).ready(function () {
$.get('/Dashboard/GetResources', function (data) {
scope.Resources = data;
scope.energyOptions = [{ name: scope.Resources.Electricity, id: "Electricity" }, { name: scope.Resources.Gas, id: "Gas" },
{ name: scope.Resources.Water, id: "Water" }, { name: scope.Resources.Solar, id: "Solar" }];
scope.energy = scope.energyOptions[0];
energyChosen = scope.energy.id;
scope.$apply();
});
It works except that a blank option is preselected which disappears when i select an option
I would like to be able to preselect one option. I thought that
scope.energy = scope.energyOptions[0];
would do the trick but it didn't. How can i preselect an option in this case ?
The way you are doing your ng-options it will store the name of the option in scope.energy not the whole option. You were on the right track when you did:
scope.energy = scope.energyOptions[0];
But it won't work because it expects scope.energy to be the name and not the whole option. What you want to do in your ng-options is something like:
<select id="energySource" ng-options="o as on.name for o in energyOptions" ng-model="energy" ng-selected="energy" ng-change="energyChange();"></select>
The important change is the addition of the o as o.name. The 'o' on the left is what will actually be selected and stored in your scope.energy, while the as o.name is the text that will be displayed on your pull down.
Make sure the scope.energy is outside your initialization.
$scope.energyOptions = [
{ name: "test1", id: "Electricity" },
{ name: "test2", id: "Gas" },
{ name: "test3", id: "Water" },
{ name: "test4", id: "Solar" }];
$scope.energy = $scope.energyOptions[2];

Kendo ListView search doesn't work properly with filtered data

I have a datasource with a filter applied to it. When I enable filterable search for the listview, it wipes out the original filter on the datasource. How can I get it to search WITHIN the filtered data subset?
Here is the issue in action: http://jsfiddle.net/KS7dB/. It is filtered by {b: "2B"}. Start entering "ds" in the search and it wipes out the filter and starts searching everything instead of only the filtered subset. Any idea on how to fix this behavior?
var ds1 = new kendo.data.DataSource({
data: [{
stagename: "ds1 A",
b: "1b"
}, {
stagename: "ds1 B",
b: "2b"
}, {
stagename: "ds1 C",
b: "2b"
}, {
stagename: "ds1 D",
b: "2c"
}, {
stagename: "ds1 E",
b: "2c"
}],
filter: {
field: 'b',
operator: 'eq',
value: '2b'
}
});
$("#stages_listview").kendoMobileListView({
dataSource: ds1,
template: $("#stages_listview_template1").html(),
filterable: {
field: 'stagename',
operator: 'contains',
ignoreCase: true
}
});
I did spent some time digging into this and the problem is that as soon as you create filter on your listview, in practice that is a filter on the underlining data source, they are not two separate cumulative filters . Therefore behaviour you observed seems to be correct.
Work around options:
override the filter function on the data source so it takes argument
passed to it via listview and always append the default data source
filter. Something alongside these lines. I have to admit I didn't
manage to craft final and functional solution.
lw.dataSource.filter = function() {
arguments[arguments.length]= { field: "b", operator: "eq", value: "2b" };
arguments.length += 1;
var result = lw.dataSource.originalfilter.apply(this, arguments);
return result;
}
filter server side

Programmatically Set Constructor Parameters in Javascript

I am trying to interact with a javascript api (bare in mind I have never done this before). An example of what I am attempting to work with is here:
SearchSpring.Catalog.init({
leaveInitialResults : true,
facets : '.leftNav',
results : '#results',
result_layout: 'list',
results_per_page : 12,
layout: 'top',
loadCSS: false,
filters: {
color: ['Blue']
},
backgroundFilters: {
category: ['Shirt', 'Shoes'],
department: ['Mens']
},
maxFacets: 5,
maxFacetOptions: 10,
sortText: 'Sort By ',
sortType: 'dropdown',
filterText: 'Refine Search Results',
previousText: 'Previous',
scrollType: 'scroll',
scrollTo: 'body',
backgroundSortField: 'price',
backgroundSortDir: 'desc',
compareText: 'Compare Items',
summaryText: 'Current Filters',
showSummary: true,
subSearchText: 'Subsearch:',
showSubSearch: true,
forwardSingle: false,
afterResultsChange: function() { $('.pagination').hide(); },
filterData: function(data) { console.debug(data); }
});
In the example I want to add a "backgroundFilter" to this with a value:
var cat="MyNewCategory";
cat.value="ANewValue;
How would I add this category and value to the backgroundFilters: listed above?
This is a very common framework initialization pattern when working with frameworks.
Your example code is passing a JavaScript Object {} as a parameter into a function () that is called init.
Taking out all definitions the pattern looks like this:
SomeFramework.frameworkFunction({});
In the above code the {} is an empty object used for initialization. There are two ways that you can work with that object in practice.
Regarding your first code snippet, you can add code into that 'object literal'.
backgroundFilters: {
category: ['Shirt', 'Shoes'],
department: ['Mens'],
cat: ['My value']
},
Notice the added comma, this is an important tripping point. This may or may not fit your needs, depending on a few factors.
Regarding your second code snippet, you can apply members to JavaScript objects at runtime. What I mean is, your var cat can be added to the anonymous object-literal that is being passed in. Hard to say, but a simple concept. Here is how:
//Say this is initialized in some separate way. //There is a bug here I'll describe later.
var cat="MyNewCategory";
cat.value="ANewValue";
//Extract and name the initialization object. It is verbatim at this point.
var initObject = {
leaveInitialResults : true,
facets : '.leftNav',
results : '#results',
result_layout: 'list',
results_per_page : 12,
layout: 'top',
loadCSS: false,
filters: {
color: ['Blue']
},
backgroundFilters: {
category: ['Shirt', 'Shoes'],
department: ['Mens']
},
maxFacets: 5,
maxFacetOptions: 10,
sortText: 'Sort By ',
sortType: 'dropdown',
filterText: 'Refine Search Results',
previousText: 'Previous',
scrollType: 'scroll',
scrollTo: 'body',
backgroundSortField: 'price',
backgroundSortDir: 'desc',
compareText: 'Compare Items',
summaryText: 'Current Filters',
showSummary: true,
subSearchText: 'Subsearch:',
showSubSearch: true,
forwardSingle: false,
afterResultsChange: function() { $('.pagination').hide(); },
filterData: function(data) { console.debug(data); }
};
//Now we can add variables (and functions) dynamically at runtime.
initObject.cat = cat;
//And pass them into the framework initialization in a separated way.
SearchSpring.Catalog.init(initObject);
Now for the bug. I don't know the solution because I do not know what it is intended to do, but I can point out what is potentially incorrect.
var cat="MyNewCategory";
cat.value="ANewValue;
This code is: 1 creating a String Object called cat. 2 changing the value to a new string.
I do not think this is what you really want.
To add a new backgroundFilter, in the separated way above, it would be:
initObject.backgroundFilters.cat = ['A', 'B'];
//Line above would give you this type of definition within the initObject (at runtime):
backgroundFilters: {
category: ['Shirt', 'Shoes'],
department: ['Mens'],
cat: ['A','B']
},
For this to work it will depend on what the framework is expecting regarding backgroundFilters.
Hope that helps.
All the best!
Nash
I don't quite understand - do you want to have the backgroundFilters categories as structured objects rather than plain strings? If you are in control of the entire API, you can do something like
...
backgroundFilters: {
category: [
new SearchSpring.Catalog.Category("Shirt"),
new SearchSpring.Catalog.Category("Shoes"),
new SearchSpring.Catalog.Category("MyNewCategory", "ANewValue")
],
department: 'Mens'
}
...

Categories