Improve Dynamic Dropdown Solution - javascript

I've created a dynamic dropdown list with jQuery and JavaScript. I'm hoping someone can take a look and let me know if this is an appropriate way to handle this type of task. I'm specifically curious to know if this code is scalable, and will it perform well? Next, would it be suggested to use a switch statement instead of several if statements in the JavaScript I have below? If so, why? I'd like to store this to be reused anytime I implement a solution like this, but as I'm new to JavaScript I don't completely trust my work yet.
JSFIDDLE: http://jsfiddle.net/6vrpF/
HTML:
<select id='parent'>
<option value='test'>test</option>
<option value='sure'>sure</option>
<option value='cool'>cool</option>
<option value='best'>best</option>
</select>
<select id='child'>
</select>
JavaScript:
function newDropdown()
{
var html = ""
for(i=0; i<arguments.length; i++)
{
html += "<option value='"+arguments[i]+"'>"+arguments[i]+"</option>"
}
$("#child").append(html)
}
$("#parent").on("change",function(){
$('#child').text("")
var selection = $("#parent").val()
if(selection == 'test') {newDropdown('a','b','c')}
if(selection == 'sure') {newDropdown('d','e','f')}
if(selection == 'cool') {newDropdown('g','h','i')}
if(selection == 'best') {newDropdown('j','k','l')}
});

updated the fiddle
http://jsfiddle.net/6vrpF/4/
var parentChild = {
"test" :['a','b','c'],
"sure" :['d','e','f'],
"cool" :['g','h','i'],
"best" :['j','k','l']
};
function newDropdown()
{
var html = ""
for(i=0; i<arguments.length; i++)
{
html += "<option value='"+arguments[i]+"'>"+arguments[i]+"</option>"
}
$("#child").append(html)
}
$("#parent").on("change",function(){
$('#child').text("")
var selection = $("#parent").val();
newDropdown( parentChild[selection].join(",") );
});
You need to get your data in the JSON format as mentioned/defined above
Edit: this is the updated fiddle which will give options one by one
http://jsfiddle.net/6vrpF/6/
var parentChild = {
"test" :['a','b','c'],
"sure" :['d','e','f'],
"cool" :['g','h','i'],
"best" :['j','k','l']
};
function newDropdown()
{
var array = arguments[0];
var html = ""
for(i=0; i<array.length; i++)
{
html += "<option value='"+array[i]+"'>"+array[i]+"</option>"
}
$("#child").append(html)
}
$("#parent").on("change",function(){
$('#child').text("")
var selection = $("#parent").val();
newDropdown( parentChild[selection] );
});

Related

Populate HTML Select options based on other HTML Select

Goal:
In a sidebar, display two <select> options for a form. The second <select> is dependent on the choice of the first. The second <select> will call the appropriate array from Google Apps Script.
Problem:
I cannot get the array to populate using eventlistener, by attempting google.run, or by referring to another function.
Example:
Below I have three <select> fields. The first is the primary. The second is a traditional array that is dependent on the first. The third <select> is where I cannot get the pulled arrays from the Apps Script server-side code. Keep in mind, I'm trying to pull different arrays based off of the 1st <select>.
//Google Apps Script
function Array1() {
var rng = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('perTwo').getValues();
Logger.log(rng);
return rng;
}
function getValuesForRngActive(students_active) {
var rngValues = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('students_active').getValues();
return rngValues.sort();
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Entry Selection</h2>
<hr> Period:
<select id="slct1" onchange="populate('slct1','slct2'); populate2('slct3')">
<option value=""></option>
<option value="1">Per 1</option>
<option value="2">Per 2</option>
<option value="3">Per 3</option>
</select>
<hr> Student:
<select id="slct2" onchange="myFunction()"></select>
<hr> New Dependent:
<select id="slct3"></select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
</body>
<script>
function populate(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if(s1.value == "1") {
var optionArray = ["i10", "i20", "Verna"];
}
else if (s1.value == "2") {
var optionArray = ["Last2, First2", "Student, Ima", ""];
}
else if (s1.value == "3") {
var optionArray = ["i10", "i20", "Verna"];
}
for (var i = 0; i < optionArray.length; i++) {
var newOption = document.createElement('option');
newOption.value = optionArray[i];
newOption.innerHTML = optionArray[i];
s2.appendChild(newOption);
}
}
function myFunction() {
var x = document.getElementById("slct2").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
function populate2(s3) {
var s1 = document.getElementById('slct1');
var s3 = document.getElementById(s3);
s3.innerHTML = "";
if(s1.value == "1") {
var optionArray = google.script.run.Array1();
}
else if (s1.value == "2") {
var optionArray = ["Last2, First2", "Student, Ima", ""];
}
else if (s1.value == "3") {
var optionArray = google.script.run.withSuccessHandler(onSuccess).getValuesForRngActive('students_active');
}
for (var i = 0; i < optionArray.length; i++) {
var newOption = document.createElement('option');
newOption.value = optionArray[i];
newOption.innerHTML = optionArray[i];
s3.appendChild(newOption);
}
}
</script>
<script>
// Using the "load" event to execute the function "populate"
window.addEventListener('load', populate2);
</script>
</html>
Any help would be greatly appreciated!
that App Script function should take the name of the range as parameter:
function getValuesForRange(rangeName) {
var rngValues = SpreadsheetApp
.getActiveSpreadsheet()
.getRangeByName(rangeName)
.getValues();
return rngValues.sort();
}
so that the range-name students_active can be passed into the App Script function
... and it's success handler callback probably should be populateSelectA().
google.script.run
.withSuccessHandler(populateSelectA)
.getValuesForRange('students_active');
there are a few more issues with the above code ...
while this at least would enable you to populate one <select> with <option>s.
the misconception somehow is, that these callback functions only accept a single parameter, while your populate() accepts two ...App Script should return {} or []; with JS function declarations alike function populateSelectA(data) {} & function populateSelectB(data) {}. jQuery can also be used for the client-side scripting there.

Using a javascript variable inside C# block

i am trying to get a variable by javascript and using it in my C# block but it looks like impossible.
this is my HTML:
<select class="form-control" id="Category">
#foreach (var item in Model.Categori)
{
<option value="#item.CategoriId">#item.CategoriName</option>
}
</select>
<div id="Container"></div>
and this is my javascript code:
$('#Category').on('change', function (e) {
$("#Container").append(`#foreach (var item in Model.YetkinlikKategorileri.Where(x => x.Id == $('#Category').val()))
{
<p>hello</p>
}`);
});
well is it possible to do something like that ? if not is there another way ?
You need something like this:
<script>
var data = [
#foreach (var item in dataList)
{
#Html.Raw("'"+item+"',")
}
];
$('#Category').on('change', function (e) {
var lst = data.find(/*Your condition*/);
for (var i = 0; i < lst.length; i++) {
$("#Content").append("<p>hello</p>" + data[i] + "<br/>");
}
};
</script>
dataList is the data which comes from server.
But in this way, you should get all data from server and put it into javascript data array. Then you should make lst by finding in data array.
But using ajax is better than this razor code.

How do I set dropdown option selected by looking at MVC URL

Hello and thank you for making stackoverflow such a great resource for learning programmers like me. I've been reading lots of answers on here to help with my first MVC project, this is my first time asking.
Here is my dropdown HTML
<div class="dropdown">
<select id="assetSelect" onchange="location = this.options[this.selectedIndex].value;">
<option value="/History/Index/All">All Assets</option>
#foreach (var item in Model.NodeInfo)
{
<option value="/History/Index/#item.node.name">#item.node.name</option>
}
</select>
</div>
Once an item is selected from the dropdown, the url will look like this
http://web.site/History/Index/G0000106
Now I'm trying to grab that last part of the URL (in this case G0000106) and set the corresponding dropdown option to selected. Here is the javascript I have pieced together so far but it's not working.
$('#assetSelect').find('option').each(function () {
function getCurrentPageId() {
var params = window.location.href.split('/');
var i = params.length;
var pageId = params[i];
return pageId;
}
var currentPageId = getCurrentPageId();
var $this = $(this);
if ($this.text() == currentPageId) {
$this.attr('selected', 'selected');
return false;
}
});
Will this function work with the one that populates the dropdown list? Is this the best way or is there an HTML helper that can do it? Any help is appreciated, thanks!
Option 1. You can simplify your code significantly:
function getCurrentPageId() {
var params = window.location.href.split('/');
return params[params.length - 1];
}
var pageId = getCurrentPageId();
$('#assetSelect').find('option:contains(' + pageId + ')').prop('selected', true);
Anyway, your problem was in this line:
var i = params.length;
var pageId = params[i];
It should be params[i - 1], since you want to get the last array element.
Option 2. An even simpler approach which should also work for you is to use location.pathname:
$('#assetSelect').val(window.location.pathname);

How can I generate a list of links based on dropdown menu choices?

So I've got a bunch of information for a bunch of different countries, and I'm trying to get it sorted like so:
Dropdown menu to choose a country -> Dropdown menu to choose information type -> here's a link to that information
I'm not so great with javascript, but I found this solution that allows me to change the content of the second dropdown based on the selection chosen from the first dropdown:
<script type="text/javascript">
function configureDropDownLists(ddl1, ddl2) {
var albania = new Array('History', 'Legal Guides');
var andorra = new Array('Country Overview', 'Demographics', 'Legal Guides');
switch (ddl1.value) {
case 'Albania':
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < albania.length; i++) {
createOption(document.getElementById(ddl2), albania[i], albania[i]);
}
break;
case 'Andorra':
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < andorra.length; i++) {
createOption(document.getElementById(ddl2), andorra[i], andorra[i]);
}
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
</script>
And then the dropdown boxes, in the HTML:
<select id="ddl" onchange="configureDropDownLists(this,'ddl2')">
<option value=""></option>
<option value="Albania">Albania</option>
<option value="Andorra">Andorra</option>
</select>
<select id="ddl2">
</select>
So now I'm wondering how I can take that secondary choice and use it to generate a list of links for someone to choose from--say, within a new paragraph of text or something.
First time asking a question here, sorry if confusing.
First add somewhere this link list could go.
I'd put it in a unordered list (<ul></ul>). But you could just as well put it in a paragraph or a div.
I assume you know about objects and the for / in loop.
If not, this should help you get it:
https://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/
Here is the code I made for you. I have commented it along the way.
Just ask if something is unclear :)
Albania
Andorra
<select id="ddl2" onchange="configureDropDownLists('ddl2')">
</select>
<ul id='linkList'></ul>
<script type="text/javascript">
function configureDropDownLists(ddlBeingChanged) {
var ddl = document.getElementById('ddlBeingChanged');
var ddl1ChosenValue=document.getElementById('ddl1').value;
var linkLists = {
albania: {
"history": ['http://albania.example.com/history', 'http://albania.example.com/historyTwo'],
"legal guides": ['http://albania.example.com/guide', 'http://albania.example.com/guideTwo'],
},
andorra: {
"country overview": ['http://andorra.example.com/country', 'http://andorra.example.com/overview'],
"demographics": ['http://andorra.example.com/demographics', 'http://andorra.example.com/demographicsTwo'],
"legal guides": ['http://andorra.example.com/guide', 'http://andorra.example.com/guideTwo'],
}
};
if (ddlBeingChanged == "ddl1") {
console.log(ddl1ChosenValue);
for (var ddl2 in linkLists[ddl1ChosenValue]){
console.log(ddl2);
// Here the ddl2 variable will contain the first level of the object 'linkLists'. I.E. the country names.
createOption(document.getElementById('ddl2'), ddl2, ddl2);
}
} else if (ddlBeingChanged == "ddl2") {
var ddl2ChosenValue=document.getElementById('ddl2').value;
var linkArray=linkLists[ddl1ChosenValue][ddl2ChosenValue];
// The linkArray:
// Let's say someone chose andorra and demographics
// then linkLists[ddl1ChosenValue][ddl2ChosenValue] would be equivalent to linkLists.andorra.demographics
var linkListHTML="";
for (var i in linkArray){
var URL=linkArray[i];
linkListHTML+="<li><a href='"+URL+"'>"+URL+"</a></li>";
}
document.getElementById('linkList').innerHTML=linkListHTML;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
</script>
Edit: Fixed code bugs

Javascript find missing select value

I have the following JavaScript:
var next_user = "1";
i=0;
for (i=0;i<=10;i++)
{
var el = document.getElementById("user_list");
var val = el[i].value;
if (val <= next_user)
{
next_user = i;
}
if (val >= next_user)
{
next_user = i;
}
alert(next_user);
}
and I have following Select box on the screen:
<select id="user_list" onclick="load_user(this)" name="user_list" size="21" style="width:200px;">
<option value="1">Bob</option>
<option value="2">john</option>
<option value="3">Frank</option>
<option value="5">tom</option>
</select>
I can't seem to get it working the way I want it to.
The select box could have 10 users in the list and each of the (options) values are unique (1-10).
as you can see in my select box I am missing value 4. My Javascript code from above is meant to go though the select box and find the first value that is missing. (in my above example, it should reply back with 4 as that is missing) but If Bob is missing then it should reply back with 1.
Well that's what my JavaScript code above should be doing but I can't seem to work out what I am doing wrong. (well I hope I am doing it correct)
does anyone know what I am doing wrong?
(I am not plaining to use any jQuery at this stage)
You should use options property of that select element you extracted.
Example:
<script>
var userList = document.getElementById("user_list");
for (var i=0;i<userList.options.length; i++) {
if (userList.options[i].value != (i+1)) {
alert((i+1)+" is missing");
break;
}
}
</script>
You can use the following code to alert the missing Option
var next_user = 1;
var el = document.getElementById("user_list");
for (i = 0; i < 10; i++) {
var val = parseInt(el[i].value);
if (val > next_user) {
alert(next_user);
break;
} else {
next_user++;
}
}​
Demo: http://jsfiddle.net/joycse06/75kM7/

Categories

Resources