javascript: dynamic drop down menu values - javascript

i want to create two drop down form and if i select an item on the first menu the second menu will display corresponding value. for example: if i select "fruit" on the first menu, then the second menu will display "apple", "banana" and so on. it must have values on them so i can insert it into database.
html is as follows:
<select id="firstmenu" name="fruit">
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<br/>
<select id="secondmenu" name="vegetable">
<option value="carrot">carrot</option>
<option value="celery">celery</option>
</select>
javascript; i was thinking using something like this but i lack understanding of javascript
<script>
var a=document.forms["myform"]["fruit"].value;
var b=document.forms["myform"]["vegetable"].value;
if (a=="fruit")
{
...
}
</script>
could someone give me a code example? help is much appreciated, thanks.

Well,
how about using jQuery?
var items = [{
name: '---',
value: '',
subitems: []
},
{
name: 'Fruit',
value: 'fruit',
subitems: [{
name: 'Apple',
value: 'apple'
},
{
name: 'Banana',
value: 'banana'
}
]
},
{
name: 'Vegetable',
value: 'vegetable',
subitems: [{
name: 'Carrot',
value: 'carrot'
},
{
name: 'Celery',
value: 'celery'
}
]
}
];
$(function() {
var temp = {};
$.each(items, function() {
$("<option />")
.attr("value", this.value)
.html(this.name)
.appendTo("#firstmenu");
temp[this.value] = this.subitems;
});
$("#firstmenu").change(function() {
var value = $(this).val();
var menu = $("#secondmenu");
menu.empty();
$.each(temp[value], function() {
$("<option />")
.attr("value", this.value)
.html(this.name)
.appendTo(menu);
});
}).change();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="firstmenu" name="fruit"></select>
<br/>
<select id="secondmenu" name="vegetable"></select>

I used Javascript to create a dropdown menu. Then, if the user chose fruit in the main dropdown menu, I created "fruit" options, and if the user chose vegetables in the main dropdown menu, I created "vegetable" options.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function displayAccordingly() {
//Call mainMenu the main dropdown menu
var mainMenu = document.getElementById('mainMenu');
//Create the new dropdown menu
var whereToPut = document.getElementById('myDiv');
var newDropdown = document.createElement('select');
newDropdown.setAttribute('id',"newDropdownMenu");
whereToPut.appendChild(newDropdown);
if (mainMenu.value == "fruit") { //The person chose fruit
//Add an option called "Apple"
var optionApple=document.createElement("option");
optionApple.text="Apple";
newDropdown.add(optionApple,newDropdown.options[null]);
//Add an option called "Banana"
var optionBanana=document.createElement("option");
optionBanana.text="Banana";
newDropdown.add(optionBanana,newDropdown.options[null]);
} else if (mainMenu.value == "vegetable") { //The person chose vegetabes
//Add an option called "Spinach"
var optionSpinach=document.createElement("option");
optionSpinach.text="Spinach";
newDropdown.add(optionSpinach,newDropdown.options[null]);
//Add an option called "Zucchini"
var optionZucchini=document.createElement("option");
optionZucchini.text="Zucchini";
newDropdown.add(optionZucchini,newDropdown.options[null]);
}
}
</script>
</head>
<body>
<select id="mainMenu" onchange="displayAccordingly()">
<option value="">--</option>
<option value="fruit">Fruit</option>
<option value="vegetable">Vegetable</option>
</select>
<div id="myDiv"></div>
</body>
</html>
Every time the value of the dropdown menu changes, the function displayAccordingly() runs. It creates a new dropdown menu, and then, if the value of the main dropdown menu is fruit, it adds fruit options to the newly-created dropdown menu, and if the value of the main dropdown menu is vegetables, then it adds vegetable options to the newly-created dropdown menu.
I hope this helps! :)
EDIT: If you change the value of the dropdown twice, it creates 2 dropdown menus. I added another variable to fix that:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var created = 0;
function displayAccordingly() {
if (created == 1) {
removeDrop();
}
//Call mainMenu the main dropdown menu
var mainMenu = document.getElementById('mainMenu');
//Create the new dropdown menu
var whereToPut = document.getElementById('myDiv');
var newDropdown = document.createElement('select');
newDropdown.setAttribute('id',"newDropdownMenu");
whereToPut.appendChild(newDropdown);
if (mainMenu.value == "fruit") { //The person chose fruit
//Add an option called "Apple"
var optionApple=document.createElement("option");
optionApple.text="Apple";
newDropdown.add(optionApple,newDropdown.options[null]);
//Add an option called "Banana"
var optionBanana=document.createElement("option");
optionBanana.text="Banana";
newDropdown.add(optionBanana,newDropdown.options[null]);
} else if (mainMenu.value == "vegetable") { //The person chose vegetabes
//Add an option called "Spinach"
var optionSpinach=document.createElement("option");
optionSpinach.text="Spinach";
newDropdown.add(optionSpinach,newDropdown.options[null]);
//Add an option called "Zucchini"
var optionZucchini=document.createElement("option");
optionZucchini.text="Zucchini";
newDropdown.add(optionZucchini,newDropdown.options[null]);
}
created = 1
}
function removeDrop() {
var d = document.getElementById('myDiv');
var oldmenu = document.getElementById('newDropdownMenu');
d.removeChild(oldmenu);
}
</script>
</head>
<body>
<select id="mainMenu" onchange="displayAccordingly()">
<option value="">--</option>
<option value="fruit">Fruit</option>
<option value="vegetable">Vegetable</option>
</select>
<div id="myDiv"></div>
</body>
</html>

I guess this example may suits you requirement .Here I have set some static content for second option in dynamicdropdown() function.No problem you can make that with your dynamic content by Option object.For example
document.getElementById("subcategory").options[i] = new Option("key","value",false, false)
i will be you number of for dynamic values.
Please refer the demo part DEMO of dynamic drop down menu values
<html>
<head>
<title>Create dyanamic dropdown list in javascript</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
function dynamicdropdown(listindex)
{
document.getElementById("subcategory").length = 0;
switch (listindex)
{
case "fruits" :
document.getElementById("subcategory").options[0]=new Option("Please select fruits","");
document.getElementById("subcategory").options[1]=new Option("apple","apple");
document.getElementById("subcategory").options[2]=new Option("banana","banana");
document.getElementById("subcategory").options[3]=new Option("mangoes","mangoes");
break;
case "meats" :
document.getElementById("subcategory").options[0]=new Option("Please select meats","");
document.getElementById("subcategory").options[1]=new Option("pigs","pigs");
document.getElementById("subcategory").options[2]=new Option("chicken","chicken");
break;
}
return true;
}
</script>
</head>
<title>Dynamic Drop Down List</title>
<body>
<div class="category_div" id="category_div">Please specify food items:
<select name="category" class="required-entry" id="category" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="">Select food items</option>
<option value="Php">fruits</option>
<option value="Javascript">meats</option>
</select>
</div>
<div class="sub_category_div" id="sub_category_div">Please select foods:
<script type="text/javascript" language="JavaScript">
document.write('<select name="subcategory" id="subcategory"><option value="">Please select foods</option></select>')
</script>
<noscript>
<select name="subcategory" id="subcategory" >
<option value="">Please select foods</option>
</select>
</noscript>
</div>
</body>
</html>
Also refer for more details: Reference

i am a little confused about your problem, but i just wrote two sample examples for you DEMO1 and DEMO2
DEMO1 - javascript
window.onload = function() {
document.getElementById("firstmenu").addEventListener('change',function(e) {ha(e,'firstmenu','secondmenu');}, false);
};
function ha(e,first,second){
var firstOptions = document.getElementById(first).options;
var secondOptions = document.getElementById(second).options;
for(var i = 1, j = firstOptions.length; i < j; i++) {
secondOptions[i].value = firstOptions[i].value;
secondOptions[i].text = firstOptions[i].text;
}
};
DEMO2 - javascript
window.onload = function() {
document.getElementById("firstmenu").addEventListener('change',function(e) {ha(e,'secondmenu');}, false);
document.getElementById("secondmenu").addEventListener('change',function(e) {ha(e,'firstmenu');}, false);
};
function ha (e,id){
var index = e.target.selectedIndex;
document.getElementById(id).selectedIndex = index;
};
DEMO1 and DEMO2 have same HTML :
<select id="firstmenu" name="City">
<option value="--">--</option>
<option value="NY">NY</option>
<option value="LA">LA</option>
</select>
<br/>
<select id="secondmenu" name="zipCode">
<option value="--">--</option>
<option value="10001">10001(NY)</option>
<option value="90001">90001(LA)</option>
</select>
Hope this will help you !!

Related

Creating A select element and if statement to display different href

I am trying to create a drop down menu and then based on selection display a clickable link to book time with each Customer service manager ... sorry for the awful code below i pieced it together from very old knowledge and google
\\
</select>
<button onclick="message()">book a time </button>
<SCRIPT>
function message() {
var s = document.getElementById('item1');
var item1 = s.options[s.selectedIndex].value;
let bookt;
if (item1 == 1)
{ document.getElementById("demo").innerHTML= Book Kim ;
}
else if (item1 == 2)
{ bookt="ibrahim link"; }
else if (item1 == 3) {
bookt= ;}
else if (item1 == 4) {
bookt="Steff Link";}
}
</SCRIPT>
<p id="demo"></p>
</body>
</html>
\\
The following code should do it:
const select = document.getElementById('select')
const links = ['https://google.com/', 'https://apple.com/', 'https://microsoft.com/']
var selectedItem = links[0]
function update() {
const item = parseInt(selectedItem)
document.getElementById('link').innerHTML = `book a time</button>`
}
<!Doctype html>
<html>
<body>
<select id='select' onchange='selectedItem = this.value;update()'>
<option selected hidden>Choose a person</option>
<option value='1'>Person 1</option>
<option value='2'>Person 2</option>
<option value='3'>Person 3</option>
</select>
<div id='link'><button>Please choose an option!</button></div>
</body>
</html>
The links array contains the links to each page that you would like to send the user to for the selected person, who is stored inside of the dropdown menu.

Get selected item on select with js

Look, i'm getting crazy, i can't get the selected item inside a normal select dropdown list (The values of the list are created dynamiclly with js).
I have a list of items and that are the columns of a table and i want when i click on an item, the column is added to the table and if i click another time in that item the column is removed.
I've tried to use a change event with jquery and onchange event with js but if i select the item two times in a row the column is added but not removed because the value hasn't changed.
I've tried to give a onclick event to the options of the select but nothing happens when i click on one. I've tried to capturo the clicked option from the select with jquery with this code:
$("#selectTableLt").on("click", "option", function() {
let clickedOption = $(this);
console.log(clickedOption);
});
But nothing happens.
Can anyone help me with this, please? Thank you
Edit:
My html:
<select name="leftColumns" id="selectTableLt"></select>
I load the options with javascript but they look like:
<option value="opt1">Option 1</option>
It's very simple
Check this out
<!DOCTYPE html>
<html>
<head>
<title>Select from dropdown list</title>
</head>
<body>
<h1>Select from dropdown list</h1>
<p id="result">Result here</p>
<select id="country">
<option value="None">-- Select --</option>
<option value="ID1">America</option>
<option value="ID2" selected>India </option>
<option value="ID3">England</option>
</select>
<script>
function GetSelectedValue(){
var e = document.getElementById("country");
var result = e.options[e.selectedIndex].value;
document.getElementById("result").innerHTML = result;
}
function GetSelectedText(){
var e = document.getElementById("country");
var result = e.options[e.selectedIndex].text;
document.getElementById("result").innerHTML = result;
}
</script>
<br/>
<br/>
<button type="button" onclick="GetSelectedValue()">Get Selected Value</button>
<button type="button" onclick="GetSelectedText()">Get Selected Text</button>
</body>
</html>
here is a solution to handle the multiple click events and fetch the dropdown selected value
var oldValue = null;
$(document).on("click","#selectTableLt", function(){
s = $(this);
val = s.val();
if (oldValue == null) {
oldValue = val;
} else {
var newValue = s.val();
if (newValue != "") {
var finalVal = oldValue == s.val() ? oldValue : newValue;
console.log(finalVal)
}
$(document).unbind('click.valueCheck');
oldValue = null;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectTableLt">
<option value="0">One</option>
<option value="1">Two</option>
</select>
You need to fetch the value using $.val() function
bind event to document in order to handle the dynamic event listener
$(document).on( eventName, selector, function(){} );
Using the Change Event:
$(document).on("change","#selectTableLt", function() {
let clickedOption = $(this).val();
console.log(clickedOption);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectTableLt">
<option value="0">One</option>
<option value="1">Two</option>
</select>
Using the Click Event:
$(document).on("click","#selectTableLt", function() {
let clickedOption = $(this).val();
console.log(clickedOption);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectTableLt">
<option value="0">One</option>
<option value="1">Two</option>
</select>

How to use selected option is variable select list

For my code i need 2 selects, the first select is static (4 options that dont change) and the second select is dependant on what is selected in the first select.
Then depending on what is chosen in de the second list a function is executed.
i found some example code one W3schools that allow me to make the whole list thing:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_select_options3
So this works really well but now i dont know how to attach a function to the selected options in the second select since there is no where in the html to do something like an onchange.
Each option from the second select should have a function (in my code the selected option will display an image corresponding with the chosen option)
<!DOCTYPE html>
<html>
<body>
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
<select id="carmodel"></select>
<script>
var carsAndModels = {};
carsAndModels['VO'] = ['V70', 'XC60', 'XC90'];
carsAndModels['VW'] = ['Golf', 'Polo', 'Scirocco', 'Touareg'];
carsAndModels['BMW'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("car");
var modelList = document.getElementById("carmodel");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car);
}
}
}
</script>
</body>
</html>

Set <select> element depending on another <select> element

I need a select element's options to change depending on the value of another.
<select id="first">
<option value="1">one</option> // When you click this one, all the values of #second change (arbitrary number of entries)
<option value="2">two</option> // When you click this one, all the values of #second change to something else (not necessarily the same number)
</select>
<select id="second">
<option value="thisChanges">soDoesThis</option>
<option value="thisToo">andThis</option>
</select>
<script>
$("#first").on("change", function() {
<pseudo>
if #first == "1"
#second = {"this", "that", "the other"}
else if #first == "2"
#second = {"more", "even more", "yet another", "still more"}
</pseudo>
}
</script>
This is pretty much what I'm after (took me years to figure out how to completely replace the values of a select box), but the button click event doesn't even work. It was working a minute ago, although the for loop was not.
Obviously for my use case I would check if the select is clicked and retrieve its value with .val(), but I figured this button is easier for debugging.
JSFiddle
HTML:
<select id="sel">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button>
Click me
</button>
JS:
var list = ['11', 'Eleven', '12', 'Twelve', '13', 'Thirteen'];
$('button').on('click', function () {
alert('click');
var sel = $('#sel');
alert('1');
sel.empty();
alert('2');
for (i = 0, i < list.length; i+2) {
$('#sel').append('<option value="' + list[i] + '">' + list[i+1] + '</option>');
}
alert('3');
});
I think you requirement similiar to the cascading dropdownlist, if i have understood correctly.
Ex jquery code:
$(document).ready(function () {
$("#state").prop("disabled", true);
$("#country").change(function () {
if ($("#country").val() != "Please select") {
var options = {};
options.url = "/home/getstates";
options.type = "POST";
options.data = JSON.stringify({ country: $("#country").val() });
options.dataType = "json";
options.contentType = "application/json";
options.success = function (states) {
$("#state").empty();
for (var i = 0; i < states.length; i++) {
$("#state").append("<option>" + states[i] + "</option>");
}
$("#state").prop("disabled", false);
};
options.error = function () { alert("Error retrieving states!"); };
$.ajax(options);
}
else {
$("#state").empty();
$("#state").prop("disabled", true);
}
});
});
Kindly refer this good article for the complete code:
http://www.binaryintellect.net/articles/b58fde6b-415e-454d-985b-d5dc4ad2fca8.aspx
Hope it will helps
Thanks
Karthik
Since you specified jQuery, I'll give you a jQuery answer! Grab the value and the text from the selected option, and append a new one to the select:
$(document).on('change', '#two', function() {
var option_to_add = $(this).find("option:selected").text();
var number_of_options = $('#two option').length
$('#one').append($('<option>', {
value: number_of_options,
text: option_to_add
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="one">
<option value="cash">Cash</option>
<option value="money">Money</option>
</select>
<select id="two">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
<option value="op1">Should be option 1: <a id="option1"></a></option>
</select> Should also be option 1:
<div id="option1"></div>
Based on your comments and changes to your post, if you just want to replace the options in a select element using a dummy array (or array of arrays,) you can do so the following way see code comments for details:
// dummy data array of arrays
var list = [
[11, "Eleven"],
[12, "Twelve"],
[13, "Thirteen"]
];
// click the button, replace the select contents
$('#btn').on('click', function() {
// build an array of option objects from an array of arrays
// see below
var opt_array = build_opt_array(list);
$('#sel').empty();
// add the new options
$(opt_array).each(function(index) {
$('#sel').append(opt_array[index]);
});
});
// helper function
// builds a new array of option html objects from
// an array of arrays
function build_opt_array(items) {
var opt_array = [];
$(items).each(function(index) {
var new_option = $('<option>', {
value: items[index][0],
text: items[index][1]
});
opt_array.push(new_option);
});
return opt_array;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button id="btn">
Click me
</button>
To get the text found in the first Select field, use the .text() function after using find(":selected") on your desired select field.
$("#two").focus(function() {
document.getElementById("option1").innerHTML = $("#one").find(":selected").text();
});

How to make <option>s of <select> show or hide using JavaScript?

I want to make the options of < select > show or hide by program(JS),is it possible?
It is just like the interesting tags in the front page of StackOverFlow, when you type in some words, the drop list will expand and give you suggestions.
ps.I know StackOverFlow didn't use select in this case, anyway just take it as an example.
You add or remove items from the options collection of the select.
Here is an example that removes one item and adds another:
<html>
<head>
<title></title>
<script type="text/javascript">
function init() {
// get a reference to the element
var sel = document.getElementById('sel');
// remove an option
sel.options[2] = null;
// create a new option and add to the select
var opt = document.createElement('option');
opt.value = '5';
opt.text = 'five';
sel.options.add(opt);
}
</script>
</head>
<body onload="init();">
<form>
<select id="sel">
<option value="0">zero</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</form>
</body>
</html>
function getCatListdef(sel)
{
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'data.php?cat_code='+sel;
ajax[index].onCompletion = function(){ createCities(index) };
ajax[index].runAJAX();
}

Categories

Resources