JavaScript access to a dynamically created array object - javascript

I created a list of arrays dynamically, which has the following syntax:
<script>
var item1001 = new Array();
item1001[0] = 1001; //id
item1001[1] = "Item name";
item1001[2] = 500; //item price
item1001[3] = "http://whatever"; //item page link
var item1002 = new Array();
item1002[0] = 1002; //id
item1002[1] = "Item name";
item1002[2] = 600; //item price
item1002[3] = "http://whatever"; //item page link
var item1003 = new Array();
item1003[0] = 1003; //id
item1003[1] = "Item name";
item1003[2] = 700; //item price
item1003[3] = "http://whatever"; //item page link
...
</script>
Now I have a form with a SELECT populated with all the items:
<select name="items" id="items">
<option value="1001">Item name</option>
<option value="1002">Item name</option>
<option value="1003">Item name</option>
...
</select>
Just wanted to retrieve the item price when the select changes, to make some calculations with JavaScript:
jQuery( "#items" ).change(function() {
var myItemPrice="item"+Number(jQuery( "#items" ).val()+"[2]");
console.log("Item price: "+myItemPrice);
var total = Number(myItemPrice - (myItemPrice*5)/100);
console.log("Total: "+total);
});
But I don't know how to access the array, i.e. "item1001[2]" dinamically, based upon "select" value...

Just for the sake of showing how to access to a variable as a window's attribute:
var item1001 =[];
item1001[0] = 1001; //id
item1001[1] = "Item name";
item1001[2] = 500; //item price
item1001[3] = "http://whatever"; //item page link
var item1002 = [];
item1002[0] = 1002; //id
item1002[1] = "Item name";
item1002[2] = 600; //item price
item1002[3] = "http://whatever"; //item page link
var item1003 = [];
item1003[0] = 1003; //id
item1003[1] = "Item name";
item1003[2] = 700; //item price
item1003[3] = "http://whatever"; //item page link
jQuery( "#items" ).change(function() {
var myItemPrice="item"+jQuery( "#items" ).val();
console.log("Item price: "+myItemPrice);
var total = window[myItemPrice][2];
console.log("Total: "+total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="items" id="items">
<option value="1001">Item name</option>
<option value="1002">Item name</option>
<option value="1003">Item name</option>
...
</select>
But you could just store your items in an object or an array:
var items= {
"1001": ["Item name", 500],
"1002": [...],
...
}
And your event handler would be much easier:
jQuery( "#items" ).change(function() {
var myItem=jQuery( "#items" ).val();
console.log("Item price: "+items[myItem][1]);
});

Use single javascript object instead:
var items = {};
items["1001"] = {name: "...", price: 100};
items["1005"] = {name: "...", price: 500};
var price = items[$('#items').val()].price;
..

You can use window to access global scope.
window['item' + $(this).val()][2]
But better restructure your initial data. You can use object to store data
var items = {
1001: { id: 1001, name: '', price: 100},
1002: { id: 1002, name: '', price: 100}
}
var price = items[$(this).val()].price

<select name="items" id="items">
<option value="1001">Item name</option>
<option value="1002">Item name</option>
<option value="1003">Item name</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var item = {
1001 :{id:"1001", name:"Item name", price: 500, url:"http://whatever"},
1002 :{id:"1002", name:"Item name", price: 600, url:"http://whatever"},
1003 :{id:"1003", name:"Item name", price: 700, url:"http://whatever"}
};
$( "#items").change(function(){
var myItemPrice = item[$("#items").val()].price;
console.log("Item price: "+myItemPrice);
var total = myItemPrice - (myItemPrice*5)/100;
console.log("Total: "+total);
});
</script>

Related

display data in input fields based from user input

I have this simple form that display name of food based from the first input field.
It is working, but I like to add another field for category(fruit, meat, vegetable).
How can I display the category of food in the last field
ex. 1 - Apple - Fruit
Thanks
CODE
var obj = {
1:'Apple',
2:'Chicken',
3:'Carrots',
4:'Mango',
5:'Beef',
6:'Squash'
}
$('#num').on('keyup',function() {
var key = $(this).val(),
result = obj[key],
$category = $('#category')
if (result != undefined) {
$category.val(result);
} else {
$category.val('');
}
})
FIDDLE
https://jsfiddle.net/gprkzs0s/1/
how about an array of objects.
function food(id, food, category) {
var self = this;
this.id = id;
this.food = food;
this.category = category;
};
function model() {
var self = this;
this.foods = [];
}
var mymodel = new model();
$(function() {
mymodel.foods.push(new food(1, 'Apple', 'Fruit'));
mymodel.foods.push(new food(2, 'Chicken', 'Meat'));
mymodel.foods.push(new food(3, 'Carrots', 'Vegetable'));
mymodel.foods.push(new food(4, 'Mango', 'Fruit'));
mymodel.foods.push(new food(5, 'Beef', 'Meat'));
mymodel.foods.push(new food(6, 'Squash', 'Vegetable'));
$('#num').on('keyup change', function() {
var key = $(this).val();
$category = $('#category')
$food = $('#food')
$category.val('');
$food.val('');
$.each(mymodel.foods, function(index, item) {
if (item.id == key) {
$category.val(item.category);
$food.val(item.food);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="num" class="form-control" name="number" placeholder="Enter Section Number">
<input type="text" id="category" class="form-control" name="category">
<input type="text" id="food" class="form-control" name="food">

How to add values to <option> tag loaded from array

I have a multi part form to load color options based on size selection however it will not add values to the option tag and I cant seem to find the solution. What I would like is.
To add values to the option tags example:
option value="X">Clear,option value="T">Smoke,option value="GS">Gunsmoke
Output as html the selected options text so i can display to client their selections in a readable format before they submit the final step.
Any help would be greatly appreciated. Thanks
My Code
var Vest_10_08 = new Array("Select Color", "Clear", "Smoke", "Gunsmoke");
var Vest_10_10 = new Array("Select Color", "Clear", "Smoke", "Gunsmoke");
var Vest_10_12 = new Array("Select Color", "Clear", "Smoke", "Gunsmoke");
var Vest_10_14 = new Array("Select Color", "Clear", "Smoke");
var Vest_10_16 = new Array("Select Color", "Clear", "Smoke");
$(document).ready(function () {
//Populate Select Items
$('#SelectSize').change(function () {
populateSelect(), populatePart();;
});
$('#SelectHardware').change(function () {
populatePart();
});
$('#SelectColor').change(function () {
populatePart();
});
function populateSelect() {
SelectSize = $('#SelectSize').val();
$('#SelectColor').html('');
eval(SelectSize).forEach(function (t) {
$('#SelectColor').append('<option>' + t + '</option>');
});
}
function populatePart() {
SelectSize = $('#SelectSize').val();
SelectHardware = $('#SelectHardware').val();
SelectColor = $('#SelectColor').val();
document.getElementById('item_name').value = (SelectSize + '66' + SelectHardware + SelectColor)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select id="SelectSize" name="SelectSize" required="">
<option selected="selected">Select Size</option>
<option value="Vest_10_08">10 tall X 14 wide</option>
<option value="Vest_10_10">14 tall X 14 wide</option>
<option value="Vest_10_12">16 tall X 14 wide</option>
<option value="Vest_10_14">16 tall X 16 wide</option>
<option value="Vest_10_16">18 tall X 16 wide</option>
</select>
<br>
<br>
<select id="SelectHardware" name="SelectHardware" required="">
<option selected="selected">Select Hardware</option>
<option value="C">Chrome</option>
<option value="SB">Black</option>
</select>
<br>
<br>
<select id="SelectColor" name="SelectColor" required=""></select>
<br>
<br>
<input id="item_name" name="item_name" type="text" style="width: 200px" />
First of all, it's generally considered a bad practice to use eval in general. A good re-write could use objects to store your values instead of using individually named variables. You can also use objects to store the value and display properties.
Something like this...
var vestData = {
'Vest_10_08':[
{
value:'',
text:'Select Color'
},
{
value:'S',
text:'Smoke'
},
{
value:'GS',
text:'Gun Smoke'
}
],
'Vest_10_10':[
// ...
]
};
However, since you have duplicate items with the same values you might want one master object to reference the internal values to the display values like this.
var colorNames = {
'C':'Clear',
'S':'Smoke',
'GS':'Gun Smoke'
}
var colorOptions = {
'Vest_10_08':['C','S','GS'],
'Vest_10_10':['C','S','GS'],
'Vest_10_12':['C','S','GS'],
'Vest_10_14':['C','S'],
'Vest_10_16':['C','S']
};
$(document).ready(function () {
//Populate Select Items
$('#SelectSize').change(function () {
populateSelect(), populatePart();;
});
$('#SelectHardware').change(function () {
populatePart();
});
$('#SelectColor').change(function () {
populatePart();
});
function populateSelect() {
SelectSize = $('#SelectSize').val();
$('#SelectColor').html('<option value="">Select Color</option>');
colorOptions[SelectSize].forEach(function (t) {
$('#SelectColor').append('<option value="' + t + '">' + colorNames[t] + '</option>');
});
}
function populatePart() {
SelectSize = $('#SelectSize').val();
SelectHardware = $('#SelectHardware').val();
SelectColor = $('#SelectColor').val();
document.getElementById('item_name').value = (SelectSize + '66' + SelectHardware + SelectColor)
}
});
You must change your Arrays to compute objects instead of strings. E.g:
var Vest_10_08 = [
{ value: '', text: "Select Color" },
{ value: 'X', text: "Clear" },
{ value: 'T', text: "Smoke" },
{ value: 'GS', text: "Gunsmoke" }
];
And then, when you're looping through the Array:
$('#SelectColor').append('<option value="' + t.value + '">' + t.text + '</option>');
Note: Nothing to do with the question, but only a tip: I don't think it's a good idea to use eval, the way you're doing. You could simply use a keyvaluepair object, and then you'd use the ID as its key. E.g:
var vests = {
Vest_10_08: [
{ value: '', text: "Select Color" },
{ value: 'X', text: "Clear" },
{ value: 'T', text: "Smoke" },
{ value: 'GS', text: "Gunsmoke" }
],
Vest_10_10: [
/* (...) */
]
};
And then you could use it, instead of using eval, by doing:
vests[SelectSize].forEach(
var Vest_10_08 = new Array({name: "Select Color", option: 0}, {name: "Clear", option: "X"}, {name: "Smoke", option: "T"}, {name: "Gunsmoke", option: "GS"});
var Vest_10_10 = new Array({name: "Select Color", option: 0}, {name: "Clear", option: "X"}, {name: "Smoke", option: "T"}, {name: "Gunsmoke", option: "GS"});
var Vest_10_12 = new Array({name: "Select Color", option: 0}, {name: "Clear", option: "X"}, {name: "Smoke", option: "T"}, {name: "Gunsmoke", option: "GS"});
var Vest_10_14 = new Array({name: "Select Color", option: 0}, {name: "Clear", option: "X"}, {name: "Smoke", option: "T"});
var Vest_10_16 = new Array({name: "Select Color", option: 0}, {name: "Clear", option: "X"}, {name: "Smoke", option: "T"});
$(document).ready(function () {
//Populate Select Items
$('#SelectSize').change(function () {
populateSelect();
populatePart();
});
$('#SelectHardware').change(function () {
populatePart();
});
$('#SelectColor').change(function () {
populatePart();
});
function populateSelect() {
SelectSize = $('#SelectSize').val();
$('#SelectColor').html('');
eval(SelectSize).forEach(function (t) {
$('#SelectColor').append('<option value=' + t.option + '>' + t.name + '</option>');
});
}
function populatePart() {
SelectSize = $('#SelectSize').val();
SelectHardware = $('#SelectHardware').val();
SelectColor = $('#SelectColor').val();
document.getElementById('item_name').value = (SelectSize + '66' + SelectHardware + SelectColor)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="SelectSize" name="SelectSize" required="">
<option selected="selected">Select Size</option>
<option value="Vest_10_08">10 tall X 14 wide</option>
<option value="Vest_10_10">14 tall X 14 wide</option>
<option value="Vest_10_12">16 tall X 14 wide</option>
<option value="Vest_10_14">16 tall X 16 wide</option>
<option value="Vest_10_16">18 tall X 16 wide</option>
</select>
<br>
<br>
<select id="SelectHardware" name="SelectHardware" required="">
<option selected="selected">Select Hardware</option>
<option value="C">Chrome</option>
<option value="SB">Black</option>
</select>
<br>
<br>
<select id="SelectColor" name="SelectColor" required=""></select>
<br>
<br>
<input id="item_name" name="item_name" type="text" style="width: 200px" />
Just put your Colors detail inside another object. You need not to duplicate all colors value inside all "Vest_10_*"
var Vest_10_08 = new Array("Select Color", "Clear", "Smoke", "Gunsmoke");
var Vest_10_10 = new Array("Select Color", "Clear", "Smoke", "Gunsmoke");
var Vest_10_12 = new Array("Select Color", "Clear", "Smoke", "Gunsmoke");
var Vest_10_14 = new Array("Select Color", "Clear", "Smoke");
var Vest_10_16 = new Array("Select Color", "Clear", "Smoke");
//New added
var Colors = {};
Colors['Select Color'] = '0';
Colors['Clear'] = 'X';
Colors['Smoke'] = 'T';
Colors['Gunsmoke'] = 'GS';
$(document).ready(function () {
//Populate Select Items
$('#SelectSize').change(function () {
populateSelect(), populatePart();;
});
$('#SelectHardware').change(function () {
populatePart();
});
$('#SelectColor').change(function () {
populatePart();
});
function populateSelect() {
SelectSize = $('#SelectSize').val();
$('#SelectColor').html('');
//Changes in this function
eval(SelectSize).forEach(function (t) {
console.log(t);
var value = Colors[t];
console.log(value);
$('#SelectColor').append('<option value="'+value+'">' + t + '</option>');
});
}
function populatePart() {
SelectSize = $('#SelectSize').val();
SelectHardware = $('#SelectHardware').val();
SelectColor = $('#SelectColor').val();
document.getElementById('item_name').value = (SelectSize + '66' + SelectHardware + SelectColor)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select id="SelectSize" name="SelectSize" required="">
<option selected="selected">Select Size</option>
<option value="Vest_10_08">10 tall X 14 wide</option>
<option value="Vest_10_10">14 tall X 14 wide</option>
<option value="Vest_10_12">16 tall X 14 wide</option>
<option value="Vest_10_14">16 tall X 16 wide</option>
<option value="Vest_10_16">18 tall X 16 wide</option>
</select>
<br>
<br>
<select id="SelectHardware" name="SelectHardware" required="">
<option selected="selected">Select Hardware</option>
<option value="C">Chrome</option>
<option value="SB">Black</option>
</select>
<br>
<br>
<select id="SelectColor" name="SelectColor" required=""></select>
<br>
<br>
<input id="item_name" name="item_name" type="text" style="width: 200px" />
If you want to avoid "eval" than code is here :
http://jsfiddle.net/bhushankumar/0b4azsuf/2/
Use a template libary like underscore or handlebars or mustache. Its bad practice to generate html from javascript.
You can format your input in javascript and construct and object with array inside :
var choices = {1:["oneValue", "twoValue"], 2:["oneHtml", "twoHtml"]};
function addInputSelect(divName) {
var newDiv = document.createElement('div');
var selectHTML = "";
selectHTML="<select>";
for(i = 0; i < choices.length; i = i + 1) {
/* choices[1][i] for get the first object in array position i */
selectHTML += "<option value='" + choices[1][i] + "'>" + choices[2][i] + "</option>";
}
selectHTML += "</select>";
newDiv.innerHTML = selectHTML;
/* append the html constructed to the dom. (divName is the html div dynamicInput) */
document.getElementById(divName).appendChild(newDiv);
}
<!-- html -->
<div id="dynamicInput"></div>
<input type="button" value="Add" onclick="addInput('dynamicInput');" />

How to create a select that depends on the value of another select?

I need to create a menu of regions hat display two lists: a <select> for the region and another <select> for the available municipalities of that region. For this, I have a <form> and I update the municipalities through JavaScript. I have problems assigning the municipalities as <option>s of the second <select>. The option matrix of the menu doesn't accept the assignment of the values.
Here's the code.
HTML.
<html>
<head>
<title>
Página menú principal.
</title>
<?!= incluirArchivo('ArchivoJS'); ?>
</head>
<body onLoad = "preparar();">
<form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on">
<select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();">
<option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option>
<option value="0">Antioquia</option>
<option value="1">Atlántico</option>
</select>
<select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled>
<option value=0>TODOS LOS MUNICIPIOS</option>
</select>
</form>
</body>
</html>
Javascript code:
<script lenguage="javascript">
function preparar() {
document.forms[0].elements.numeroLicencia.focus();
document.forms[0].elements.nombreConductor.disabled = true;
document.forms[0].elements.botonEnviar.disabled = true;
document.forms[0].elements.botonActualizar.disabled = true;
}
function municipiosDepartamento() {
var arregloMunicipiosDepartamento = new Array();
var posicionMunicipio = document.forms[0].elements.menuDepartamento.value;
arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio);
if(document.forms[0].elements.menuMunicipios.options.length > 1){
var totalMunicipios = document.forms[0].elements.menuMunicipios.length;
for (var i = 1; i < totalMunicipios; i ++){
document.forms[0].elements.menuMunicipios.options[1] = null;
}
}
if(document.forms[0].elements.menuDepartamento.value === "x"){
document.forms[0].elements.menuMunicipios.selectedItem = 0;
document.forms[0].elements.menuMunicipios.disabled = true;
}
else
{
document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length;
for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) {
var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1));
***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text;
document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;***
}
document.forms[0].elements.menuMunicipios.disabled = false;
}
}
function municipiosColombia(posicion) {
var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array();
antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"];
atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"];
arregloTodos = [antioquia, atlantico];
arregloMunicipiosDepartamento=arregloTodos[posicion];
return arregloMunicipiosDepartamento;
}
</script>
I have highlighted the work that doesn't work.
The way I would do what you describe is to clear out the options each time and recreate the required ones, then add them into the particular select, like so:
var regions = {};
regions['A'] = ['mu', 'ni', 'ci', 'pal', 'it', 'y'];
regions['B'] = ['I', 'like', 'bananas'];
var selRegion = document.getElementById('region');
selRegion.onchange = setMunicipalities;
var selMun = document.getElementById('municipality');
function setMunicipalities(e)
{
while(selMun.length > 0)
{
selMun.remove(0);
}
if(selRegion.selectedOptions[0].value === 'ALL')
{
for(var r in regions)
{
if(regions.hasOwnProperty(r))
{
addMunicipalities(regions[r]);
}
}
}
else
{
var reg = selRegion.selectedOptions[0].value;
addMunicipalities(regions[reg]);
}
}
function addMunicipalities(region)
{
var allMun = document.createElement('option');
allMun.setAttribute('value', 'ALL');
var allMunText = document.createTextNode('ALL');
allMun.appendChild(allMunText);
selMun.add(allMun);
for (var mi = 0; mi < region.length; mi++)
{
var m = region[mi];
var mun = document.createElement('option');
mun.setAttribute('value', m);
var munText = document.createTextNode(m);
mun.appendChild(munText);
selMun.add(mun);
}
}
setMunicipalities(null);
<label for="region">Region</label>
<select id="region">
<option selected="selected" value="ALL">ALL</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<label for="municipality">Municipality</label>
<select id="municipality">
</select>
I haven't read your entire code because I had a hard time reading code with contents not in English but anyway, I get what you're trying to do here. Suppose that your first select list contains "Region A" and "Region B" as options; "Municipality A1", "Municipality A2", "Municipality B1","Municipality B2" are the possible options for the second select list. Here's a function that will change the options of the second select list depending on what is selected on the first select list:
function optionChanger(v_selected){
var whatisselected= v_selected.options[v_selected.selectedIndex].value;
var municipalities= {};
municipalities['A'] = ['Municipality A1','Municipality A2'];
municipalities['B'] = ['Municipality B1','Municipality B2'];
v_selected.options.length=0; //remove the contents of the second select list
v_selected.options[0] = new Option(municipalities[whatisselected][0],municipalities[whatisselected][0],false,true);// set the first option of the second list as the default selected value
for(x=1;x<municipalities[whatisselected].length;x++){ //add the remaining options to the second list
v_selected.options[x] = new Option(municipalities[whatisselected][x],municipalities[whatisselected][x],false,false);
}
}
Then add this inside the tag of your FIRST select list:
onchange='optionChanger(this)'
PS: Please notice that the return value of the first select list must be 'A', 'B'

Drop down menu for selecting country then states then district

I am not able to design the function "print_district" to get the values from s_b.
Kindly help me to defined this multidimensional array.
I suppose to get c11,c12,c13,... on selection from C1 from country country 1 and c21,c22,c23,... on selecting C2 from country 1
But I am getting d11,d12,d13,... and d12,d22,23 so on which is from country 2
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type= "text/javascript">
var country_arr = new Array("country 1", "country 2");
var s_a = new Array();
s_a[0]="";
s_a[1]="C1|C2";
s_a[2]="D1|D2";
var s_b = new Array();
s_b[1,1]="c11|c12|c13|c14|c15|c16|c17|c18|c19|c10";
s_b[1,2]="c21|c22|c23|c24|c25|c26|c27|c28|c29|c210";
s_b[2,1]="d11|d12|d13|d14|d15|d16|d17|d18|d19|d10";
s_b[2,2]="d21|d22|d23|d24|d25|d26|d27|d28|d29|d210";
function print_country(country_id){
// given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option('Select Country','');
option_str.selectedIndex = 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
}
}
function print_state(state_id, state_index){
var option_str = document.getElementById(state_id);
option_str.length=0;
option_str.options[0] = new Option('Select State','');
option_str.selectedIndex = 0;
var state_arr = s_a[state_index].split("|");
for (var i=0; i<state_arr.length; i++) {
option_str.options[option_str.length] = new Option(state_arr[i],state_arr[i]);
}
}
//This function is incorrect, just to demonstrate, please help to correct this
function print_district(district_id, district_index){
var option_str = document.getElementById(district_id);
option_str.length=0;
option_str.options[0] = new Option('Select district','');
option_str.selectedIndex = 0;
var district_arr = s_b[district_index].split("|");
for (var i=0; i<district_arr.length; i++) {
option_str.options[option_str.length] = new Option(district_arr[i],district_arr[i]);
}
}
</script>
</head>
<body>
<form>
Select Country: <select onchange="print_state('state',this.selectedIndex);" id="country" name ="country" ></select>
<br />
State: <select onchange="print_district('district',this.selectedIndex);" name ="state" id ="state"></select>
<br />
District <select name ="district" id ="district"></select>
<input type="submit"></form>
<script language="javascript">print_country("country");</script>
</body>
</html>
Thanks in advance !
This is the solution to the above problem
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
var stateObject = {
"Country 1": {
"C1": ["c11", "c12"],
"C2": ["c21", "c22"]
},
"Country 2": {
"D1": ["d11", "d12"],
"D2": ["d21", "d22"]
}
}
window.onload = function () {
var countySel = document.getElementById("countySel"),
stateSel = document.getElementById("stateSel"),
districtSel = document.getElementById("districtSel");
for (var country in stateObject) {
countySel.options[countySel.options.length] = new Option(country, country);
}
countySel.onchange = function () {
stateSel.length = 1; // remove all options bar first
districtSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var state in stateObject[this.value]) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
}
countySel.onchange(); // reset in case page is reloaded
stateSel.onchange = function () {
districtSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var district = stateObject[countySel.value][this.value];
for (var i = 0; i < district.length; i++) {
districtSel.options[districtSel.options.length] = new Option(district[i], district[i]);
}
}
}
</script>
</head>
<body>
<form name="myform" id="myForm">
Select Country: <select name="state" id="countySel" size="1">
<option value="" selected="selected">Select Country</option>
</select>
<br>
<br>
Select State: <select name="countrya" id="stateSel" size="1">
<option value="" selected="selected">Please select Country first</option>
</select>
<br>
<br>
Select District: <select name="district" id="districtSel" size="1">
<option value="" selected="selected">Please select State first</option>
</select><br>
<input type="submit">
</form>
</body>
</html>
Angular 5 - based example it's working. To get values use Form builder and form group.
template.html
<div>
<h2>Hello country/ state/ cities </h2>
<select (change)="countryChange($event)" >
<option>Select</option>
<option *ngFor="let c of countries" [ngValue]="c.country">{{ c.country }}</option>
</select>
<select (change)="statesChange($event)">
<option>Select</option>
<option *ngFor='let state of states' [ngValue]="state.name">{{ state.name }}</option>
</select>
<select >
<option>Select</option>
<option *ngFor='let city of cities' [ngValue]="city">{{ city }}</option>
</select>
</div>
component.ts
countries= [{
"country": "Afghanistan",
"states": [
{ "name":"Nurestan", "cities":["c1", "c2", "c3"] },
{ "name":"Oruzgan", "cities":["orc1", "oruc2", "oruc3"] },
{ "name":"Panjshir", "cities":["3c1", "3c2", "3c3"] }
]
},
{
"country": "Albania",
"states": [
{ "name": "Korce" , "cities":["c1", "c2", "c3"] },
{ "name": "Kukes", "cities":["orc1", "oruc2", "oruc3"] },
{ "name": "Lezhe","cities":["orc1", "oruc2", "oruc3"]},
{ "name": "Shkoder", "cities":["orc1", "oruc2", "oruc3"]},
{ "name": "Tirane","cities":["orc1", "oruc2", "oruc3"]}
]
},
{
"country": "Antarctica",
"states": []
}
]
states= []; cities = [];
countryChange(e){
console.log(e.target.value)
this.countries.filter(element => {
if(element.country == e.target.value){
console.log(element.states[0],"first state")
this.states = element.states;
}
});
this.cities = []
}
statesChange(evt){
console.log(evt.target.value,this.states)
this.states.filter( element =>{
if(element.name == evt.target.value){
this.cities = element.cities;
}
})
}

Choosing Object in For Loop based on Input

I want to populate select options based on the value of the previously selected option.
<label for="state" class="block">State:*</label>
<select name="state" id="state" tabindex="1">
<option value="Arizona">Arizona</option>
<option value="Arkansas">Arkansas</option>
<option value="Colorado">Colorado</option>
</select>
<label for="location" class="block">Preferred Location:*</label>
<select name="location" id="location" tabindex="2">
<option value=""></option>
</select>
Thats my html. Right now I have my js, and it works, but I'm wondering if there is a petter way.
var State = $('#state').val();
var Location = $('#location');
setOptions(State);
function setOptions(chosen){
var Location=document.myform.location;
Location.options.length=0;
var Arizona = {
0 : 'Select Location',
3 : 'Phoenix (Chandler)',
4 : 'Scottsdale',
5 : 'Tuscon'
};
var Arkansas = {
2 : 'Little Rock'
};
var Colorado = {
6 : 'Colorado Springs'
};
if(chosen=="Arizona"){
var myobject = Arizona;
}
if(chosen=="Arkansas"){
var myobject = Arkansas;
}
if(chosen=="Colorado"){
var myobject = Colorado;
}
for(index in myobject) {
Location.options[Location.options.length]=new Option(myobject[index], index);
}
Is there a way I can tell it which object to use based on the other select box?
Thanks!
Use nested objects:
var locations = {
Arizona: {
0 : 'Select Location',
3 : 'Phoenix (Chandler)',
4 : 'Scottsdale',
5 : 'Tuscon'
},
Arkansas: {
2 : 'Little Rock'
},
Colorado: {
6 : 'Colorado Springs'
}
};
var myobject = locations[chosen];
for(index in myobject) {
Location.options.push(new Option(myobject[index], index));
}

Categories