Creating variable arrays with Javascript (dyamic, drop down) - javascript

I've been searching the board for a while (both here and Google) and can't seem to find what I'm looking. (Sorry if I've missed it and this qualifies as an annoying/redundant question.)
I'm working on form that will have copious amounts of drop downs based on previous selected variable(s). I was trying to come up with an easier way than having to create the individual fields and then hide/show based on selection. Ultimately, I'm aiming for a "tree" with between 3-5 levels of menus. (Clients doing, not mine.)
What the Logic looks like:
Variables: type, offer1, offer2, insert1, insert2, insert3,...
Where [type] determines [offer1,2] which has up to 3 variables each [insert1,2,3...]
So If user selects Type A: Offer1 = Array A (Insert1 = ArrayA1, Insert2 = ArrayA2, Insert3 = null) and Offer2 = Array B (Insert4 = ArrayB4, Insert5 = null); and so on and so forth.
So far, everything I've found only seems to handle the first tier, and JS isn't exactly my forte. Any pointing in the right direction would be greatly appreciated.

In case anyone else runs across this issue, I found this solution that uses JQuery:
http://www.appelsiini.net/projects/chained

Related

How do create a related search terms?

I'm working on a school project in code.org for my CS class. I'm trying to build an app that is about the bird.(We are learning about list/arrays, loops, and traversals)
In the project I'm trying to build a search box where people can type the name of the bird and in the next page will show up the information about the bird. (Those information are from the code.org data library, it has a lot of lists of datasets that you can use to build your app)
The code looks like this:
// code.org is using ES5
var birdSearch = getText('searchInput');
for(var i = 0; i < birdNameList.length; i++) {
if (birdSearch === birdNameList[i]) {
setText('birdNameOutput', birdNameList[i]);
setText('birdDietOuput', birdDietList[i]);
setText('birdImageOutput', birdImageList[i]);
}
But I'm afraid that no one will know those bird's name because you have to search the exactly same name in the list, then my app will be useless. So I am thinking to build a thing that will show the most related name depends on the user input.
It's like if you put 'Am' in the search box and it will show 'American Goldfinch', 'American Purple Gallinule' ... under the search box.
For example:
search box: Am______
do you mean: American Goldfinch
American Purple Gallinule
...
great first question and welcome! There are a lot of things here that you may wish to consider, such as the event that triggers the search - does the search happen when you click a button or when text is typed? If it is the latter then you may also want to think about debouncing the event, which is essentially adding a slight delay to calling the method to prevent it firing too many times and causing performance related issues, though I realise that this is probably a bit further on in your learning, but definitely something worth investigating as your learning progresses.
However, to get to the point of your question, I think it is probably best to look at a filter method to filter the array of results, with something like this:
const birdSearch = getText('searchInput');
const searchList = birdNameList.filter(function(bird) {
return bird.includes('birdSearch');
});
setText('suggestionBox', 'Do you mean: ' + searchList.join(', ') + '?');
Hopefully that should give you a starter for ten!

Updating the view of a screen in AngularJS

Hey—I’m working on an angular 1.6 app, and I’ve come across an issue I’m not quite sure how to resolve. Here’s a brief discussion of the set up. The page is a form with thirty questions. There is a lot of conditional logic from the client that goes as follows: if user selects “Yes” on Q1 then show them Q2-4, if “No” on Q1, then skip to Q5. This repeats itself in the thirty question form.
I’ve come across the following scenario—what if the user selects “Yes” on Q1, answers Q2-4 and then realizes Q1 should really be “No”.
So my question is: 1) how do I clear the models? and 2) how do I update the view? So that if they decide, third time around, that Q1 should in fact be yes, Q2-Q4 are unchecked/clear/blank.
For 1) I just wrote a simple “clearAll method as follows:
function clearAll(arr){
arr.forEach(function(element){
if(element!==undefined){
element = null;
}
});
}
This clears the models but doesn’t update the view. How do I update the view so that Q2-4 are clear/empty/blank?
The idea I had is to update the view, so
$scope.$watch( myModel, function(val){
//set to null or delete?
}
But I cannot generalize this so it is flexible enough to accept an array. Any advice would be appreciated. Thanks.
For your particular problem I would use ui-router and resolve different states based on a question, i.e. state.questions and take different parameters like if you have url /questions as your base intro page (maybe weclome to questions or something), you would have /questions/1 and it would be 1st question /questions/2 would be second etc...
Then keep one list of objects on some simple service i.e.:
let questions = [];
which will persist throughout the app, later to be filled with some objects like:
{
q1: {
answers: [1,2,3]
},
{
q2: {
answers: [1,3]
}
You can always clear it after you are done with it or push new answer. Also you can check for particular answer before even loading the state, and this will give you great flexibility what you actually want.
well for ugly solution your watch maybe could work if you add watch group and timeout:
$scope.$watchGroup(arrayOfModels, (newVal, oldVal)=>{
if(newVal) {
// now do something you want with that models
// if they don't apply, try $timeout(()=> $scope.$apply());
}
})

Variable checking in JSP

I am fairly new to the JSP scene, but have been programming in other languages for a few years. I am writing an application where I am passing a different variable to java based on a selection option. My main question was where to do the variable checking to see which value to pass?
Here is my current state of value checking (I am currently rewriting it in JSTL as I found sciplets are bad practice).
if (request.getParameter("Freq").equals("Minutes")) {
runOn = request.getParameter("numberOfMinutes");
} else if (request.getParameter("Freq").equals("Weekly")) {
runOn = request.getParameter("dayOfWeek");
} else if (request.getParameter("Freq").equals("Monthly")) {
runOn = request.getParameter("dayOfMonth");
} else {
runOn = "-1";
}
Should this sort of check be done on the jsp page, in javascript, or somewhere else? Looking for a best practice kind of answer.
Side question: Right now, I create a number of different drop down boxes and hide/unhide them using an onChange function in javascript. Would it be better to have one list box where the options change in javascript or keep the current system? Essentially the list boxes are asking the user what day they want their process to run. So if frequency is weekly, a list box with the days of the week would show, but if they have month selected, a list of numbers from 1 to 31 shows. It could all be done with one list box that changes its options when the 'frequency' drop down changes. Again, I'm looking for a best practice answer?
Thank you in advance!

Get checked nodes in a jsTree

I have a working JSTree based on JSON data, and the checkbox plugin displays boxes next to each item -- so far so good. Now I want to get which nodes the user has checked, so I can do something with the data.
Unfortunately I haven't found a way to do it through the documentation or web searches. A few answers on SO say to use a get_checked method, but either I'm really missing something or my version of JSTree doesn't have that (i.e. that string doesn't appear anywhere in the project files). I'm on version 3.0.0, which is the latest right now.
Could someone please point me either to a) how to get the checked items, or b) how to access some iterable representation of the tree so I can grab them myself?
(I should mention I'm pretty new to Javascript.)
Here is how I set up the tree, which is based on the documentation on the website:
var treeInit = { core: { data : [
/* all my data */
]
}};
treeInit.plugins = ["checkbox"];
$('tree_div').jstree(treeInit);
I have also faced the same problem with jstree version 3.0.0 . I found a simple solution after hours of surfing. Hope it help others.
var result = $('#your_tree').jstree('get_selected');
This line returns an array of selected values.
I found an answer. By calling $('#tree').jstree('get_json'), you can get a JSON representation of the whole tree. From there it's pretty straight forward to recurse through the tree nodes and grab all the checked ones. Again, this is for version 3.0.0 (since it seems that the API has changed a lot across versions).
Using 3.3.8 version of jsTree, my prefered way of getting it as below using get_selected:
Please remember, it only counts those nodes that are selected, it won't count any indeterminate nodes. For complete and working sample code, you can have view https://everyething.com/Example-of-jsTree-to-get-all-checked-nodes
$('.btnGetCheckedItem').click(function(){
var checked_ids = [];
var selectedNodes = $('#SimpleJSTree').jstree("get_selected", true);
$.each(selectedNodes, function() {
checked_ids.push(this.id);
});
// You can assign checked_ids to a hidden field of a form before submitting to the server
});

my python code - for javascript?

I was wondering if someone could give me advice on this code. I have done it in python but I think I need to have it in javascript as it is for a website. I am new to programming so please be kind!
Aims of the site:
The user will have to answer 6 multiple choice questions. (Q1 has
7 possible answers but the others only have 2).
Depending on their inputs they will receive an outcome (I have just put the outcomes as range(1,225) for now but there will be different outcomes depending on the input
The outcomes and the possible input combinations are all fixed and will not change
I am pretty sure I have not done it the best way as I don't have much experience, but it seems to work so far.
Does the code look ok?
Do you think I will be able to translate this into javascript easily enough?
Should I have the table of outcomes/inputs fixed in some way so it doesn't need to be worked out by the computer every time or is it ok as it is?
Any advice or help is very much appreciated indeed.
#list of possible inputs
list = [[23,24,25,26,27,28,29],["male","female"],["true","false"],["true","false"],
["true","false"],["true","false"]]
#make a list of outcomes
outcome=[]
for i in range(1,225):
outcome.append(i)
#make a table of all possible list input combinations
r=[[]]
for e in list:
table = []
for item in e:
for i in r:
table.append(i+[item])
r = table
#make a dictionary where the input is the key and outcome is the value
adict = dict((str(r), outcome) for r, outcome in zip(r, outcome))
#dummy inputs as an example
input1 = 27
input2 = "male"
input3 = "true"
input4="true"
input5="true"
input6="true"
#put all the inputs into one string & look up outcome in adict
new_input = []
new_input.extend([input1,input2,input3,input4,input5,input6])
print adict.get(str(new_input))
There is no need to rewrite it in javascript; instead try using one of the Python web frameworks like Flask or Django.

Categories

Resources