assign value to dropdown using javascript - javascript

i have wriiten javascriot for two levels of dropdown on selecting value in first i get values in second dropdown. now what is happening the value that is there in the array is getting assigned to the second dropdown. i want to assign urls as values to the second dropdown and redirect them to those dropdowns.in my below example if i select apparel then i get men and women in second dropdown so if i select men in second dropdown it should go to xyz.com.... so for each option in second dropdown i want it to be redirected to a specific url how can i do it?
<html>
<head>
<script type="text/javascript">
var categories = [];categories["startList"] = ["Apparel","Books"]
categories["Apparel"] = ["Men","Women"];
categories["Books"] = ["Biography","Fiction","Nonfiction"];
var nLists = 2; // number of lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms[0]['List'+i].length = 1;
document.forms[0]['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
//var nurl= url[currCat]
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function getValue(isValue) {
alert(isValue);
}
function init() {
fillSelect('startList',document.forms[0]['List1'])
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
</script>
</head>
<body>
<form action="">
<select name='List1' onchange="fillSelect(this.value,this.form['List2'])">
<option selected>Make a selection</option>
</select>
<!--<select name='List2' onchange="fillSelect(this.value,this.form['List3'])">
<option selected>Make a selection</option>
</select>-->
<select name='List2' onchange="getValue(this.value)">
<option selected >Make a selection</option>
</select>
</form>
</body>
</html>

First you need to modify your source array as JSON format like this :
var categories = [];categories["startList"] = [{"text":"Apparel","url":"Apparel"},{"text":"Books","url":"Books"}]
categories["Apparel"] = [{"text":"Men","url":"xyz.com"},{"text":"Women","url":"abc.com"}];
categories["Books"] = [{"text":"Biography","url":"Biography.com"},{"text":"Fiction","url":"Fiction.com"},{"text":"Nonfiction","url":"Nonfiction.com"}];
Now, In function we can use it as key value pair :
var nLists = 2; // number of lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms[0]['List'+i].length = 1;
document.forms[0]['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
//var nurl= url[currCat]
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]["text"]);
nOption.setAttribute('value',nCat[each]["url"]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function getValue(isValue) {
//alert(isValue);
location.replace("http://" + isValue);
}
That's it !!!

Related

Create new select when somebody click in the option

There is a select with a list of countries. Choosing a country it should create new select with a list of cities from this country.
var selectCountries = document.getElementById("countries");
var options = selectCountries.options;
for( var i = 0; i < options.length; i++ ){
options[i].addEventListener("click",funct )
}
function funct(){
var mainDiv = document.getElementById("main");
var newCities = document.createElement("select");
main.appendChild(newCities);
var newOptions = document.createElement("option");
newCities.appendChild(newOptions);
}
<div id="main"> <select id="countries"> <option>France</option> <option>Germany</option> </select> </div>
My suggestion: create one <select id="cities"> then hide it, then we don't need to care about whether <select id="cities"> exists when selecting one country.
For DOM, you need to loop options under <select id="countries"> to check which option is selected. so I created one function=getSelectedValue
And I created one var citiesConfigs to save all cities, then when selecting one city, pull out all cities under the selected county.
Finally, in function=funct,
get selected option for <select id="countries">
get all cities under the selected country, loop them to create <option> then append to <select id="cities">
finally, show up <select id="cities">
var selectCountries = document.getElementById("countries");
var options = selectCountries.options;
for( var i = 0; i < options.length; i++ ){
options[i].addEventListener("click",funct )
}
var citiesConfigs = {'france': ['CityA', 'CityB'], 'germany':['CityC','CityD']}
function getSelectedValue(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].value;
}
function funct(){
var mainDiv = document.getElementById("main");
var selectedCity = document.getElementById("cities")
selectedCity.innerHTML = ''
citiesConfigs[getSelectedValue('countries')].forEach(function(city){
let newOption = document.createElement("option");
newOption.value = city
newOption.text = city
selectedCity.appendChild(newOption);
})
selectedCity.style.display = ''
}
<div id="main"> <select id="countries"> <option value="france">France</option> <option value="germany">Germany</option> </select>
<select id="cities" style="display:none"></select>
</div>

Dropdown with 4 Levels identical selections

I've this modified script I found online.
It works very well to have dropdown select menu with 4 posiblities.
The problem here. If a menu is identical like here with Mexico (for Mexico the city and Mexico the country), it won't work correctly.
How i can correct that? Thanks for help!
var categories = [];
// list1
categories["startList"] = ["America","Europe"]
// list2
categories["America"] = ["USA","Mexico"];
categories["Europe"] = ["France","UK"];
// list3
categories["USA"] = ["New York","Texas"];;
categories["Mexico"] = ["Mexico","Guadalajara"];
categories["France"] = ["Alsace","Normandie"];
categories["UK"] = ["Wales", "Scotland", "England"];
// list4
categories["New York"] = ["Manhattan","Brooklyn","Harlem","Queens"];
categories["Texas"] = ["Dallas","Eagle Pass"];
categories["Mexico"] = ["DF"];
categories["Guadalaraja"] = ["East","West"];
categories["Alsace"] = ["Strasbourg","Kronenbourg"];
categories["Normandie"] = ["Caen","Saint-Malo","Saint-Pierre","Saint-Jean"];
categories["Wales"] = ["Cardiff", "New Port"];
categories["Scotland"] = ["Edimbourg"];
categories["England"] = ["London","Manchester","Exeter","Dover"];
var nLists = 4; // number of select lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms['tripleplay']['List'+i].length = 1;
document.forms['tripleplay']['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function init() {
fillSelect('startList',document.forms['tripleplay']['List1'])
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
<form name="tripleplay" action="">
<select name='List1' onchange="fillSelect(this.value,this.form['List2'])">
<option selected>Select One</option>
</select>
<select name='List2' onchange="fillSelect(this.value,this.form['List3'])">
<option selected>Select Two</option>
</select>
<select name='List3' onchange="fillSelect(this.value, this.form['List4'])">
<option selected >Select Three</option>
</select>
<select name='List4' onchange="getValue(this.value, this.form['List3'].value, this.form['List2'].value,
this.form['List1'].value)">
<option selected >Select Four</option>
</select>
</form>
Original adaptation of https://jsfiddle.net/nbz9atmv/ and https://www.sitepoint.com/community/t/country-state-city-dropdown-list/2438
I noticed a few errors from this snippet.
I would say instead of declaring the city in Mexico as 'Mexico', why not declare it as 'Mexico City'? From what I understand this is what the city is formally recognized as and your code will recognize this as well. So, I changed 'Mexico' the city to 'Mexico City' and it worked perfectly well. This also allows your resulting code to be understood more easily by your target audience.
The second error I noticed was you had 'Guadalajara' spelled incorrectly in 'list 4'.
Also, you had getValue for the list4 select. Removed and changed to this.value. If you need to grab the value simply call the id using JS, if that was your intention.
the replace() will throw an eror but it still works properly as it sitll continues to refrain from multiple values being added to the final dropdown(list4) if changes are made to the previous dropdown(list3).
Below is the code running correctly.
Let me know if this helped!
var categories = [];
// list1
categories["startList"] = ["America","Europe"]
// list2
categories["America"] = ["USA","Mexico"];
categories["Europe"] = ["France","UK"];
// list3
categories["USA"] = ["New York","Texas"];;
categories["Mexico"] = ["Mexico City","Guadalajara"];
categories["France"] = ["Alsace","Normandy"];
categories["UK"] = ["Wales", "Scotland", "England"];
// list4
categories["New York"] = ["Manhattan","Brooklyn","Harlem","Queens"];
categories["Texas"] = ["Dallas","Eagle Pass"];
categories["Mexico City"] = ["DF"];
categories["Guadalajara"] = ["East","West"];
categories["Alsace"] = ["Strasbourg","Kronenbourg"];
categories["Normandy"] = ["Caen","Saint-Malo","Saint-Pierre","Saint-Jean"];
categories["Wales"] = ["Cardiff", "New Port"];
categories["Scotland"] = ["Edimbourg"];
categories["England"] = ["London","Manchester","Exeter","Dover"];
var nLists = 4; // number of select lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms['tripleplay']['List'+i].length = 1;
document.forms['tripleplay']['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function init() {
fillSelect('startList',document.forms['tripleplay']['List1'])
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
<form name="tripleplay" action="">
<select name='List1' onchange="fillSelect(this.value,this.form['List2'])">
<option selected>Select One</option>
</select>
<select name='List2' onchange="fillSelect(this.value,this.form['List3'])">
<option selected>Select Two</option>
</select>
<select name='List3' onchange="fillSelect(this.value, this.form['List4'])">
<option selected >Select Three</option>
</select>
<select name='List4' onchange="fillSelect(this.value, this.form['List3'].value, this.form['List2'].value,
this.form['List1'].value)">
<option selected >Select Four</option>
</select>
</form>

How do I remove old options in Jquery when parent select box is changed?

I have 3 chained select boxes using jquery and json.
Depending on first 2 values I filter third one my code actually works but the problem is when I change values of first 2 select boxes third select recieves new datas while keeping old ones.
I've tried to empty my array but it didn't work.
$(document).ready(function() {
var json = JSON.parse(jsonString);
var makesArray = [];
var selectedyear;
var selectedcourse;
var $yearDropDown = $("#DropDown_Year");
var $course_type = $("#course_type");
$yearDropDown.change(function() {
selectedyear = this.value;
//filter based on selected year.
});
$course_type.change(function(){
selectedcourse = this.value;
makesArray = jQuery.grep(json, function(course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
for(var i = 0, l = makesArray.length; i < l; i++){
var option = makesArray[i];
selectBox.options.add( new Option(option.course_code, option.course_code, option.course_code) );
}
makesArray= []; //makesArray.empty();
});
});
<div id="DrpDwn">
Year:
<select id="DropDown_Year">
<option>Yıl</option>
<option value="15">2015-2016</option>
<option value="16">2016-2017</option>
</select>
<select class="form-control" id="course_type" name="course_type" required>
<option value="" selected> Choose</option>
<option value="Yos">YÖS</option>
<option value="SatMatGeo">SAT (MAT)</option>
<option value="SatCriRea">SAT (ENG)</option>
<option value="TomerABC">TÖMER (ABC)</option>
<option value="TomerAB">TÖMER (AB)</option>
<option value="TomerBC">TÖMER (BC)</option>
<option value="TomerA1A2">TÖMER (A)</option>
<option value="TomerB1B2">TÖMER (B)</option>
<option value="TomerC1C2">TÖMER (C)</option>
</select>
Make:
<select id="DropDown_Make">
<option>None</option>
</select>
</div>
and this is JSFIDDLE
https://jsfiddle.net/rw7cb8c5/25/
Make DropDown_Make empty using selectBox.innerHTML = "" in $course_type.change() like following.
$course_type.change(function () {
selectedcourse = this.value;
makesArray = jQuery.grep(json, function (course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
selectBox.innerHTML = ""; //added this line
for (var i = 0, l = makesArray.length; i < l; i++) {
var option = makesArray[i];
selectBox.options.add(new Option(option.course_code, option.course_code, option.course_code));
}
makesArray.empty();
});
UPDATED FIDDLE

Creating multiple Select options from an Object

Im stack on creating multiple select options
I have an Object with multi objects inside and want create select options in condition of the previous select option , i provide js fiddle for better understanding .
my objectif is
first select category ----(then)---> select sex -----(then)---> select kind---(then)-->then select size
by this order from that Object.
i could do the select sex and it works but not kind and size.
this is my html
<form name="myform">
<div>
<select name="category_group" id="category_group" >
<option value="0">choose category</option>
<option value='401' > clothes </option>
<option value='403' > shoes </option>
</select>
</div>
<br>
<div>
<select id="clothing_sex" name="clothing_sex" onChange="showclothesKind(this.value,this.form.clothing_kind)">
<option value="0">choose Type»</option>
</select>
<select id="clothing_kind" name="clothing_kind">
<option value="0">choose clothes</option>
</select>
<select id="clothing_size" name="clothing_size">
<option value="0">choose size</option>
</select>
</div>
</form>
and js in the fiddle.
much appreciate your help.
This was kind of fun to play around with. Thanks for posting. I used the following:
var optionTemplate = "<option class='newOption'>sampleText</option>";
$(document).ready(function() {
var removeFromNextSelects = function(firstSelector) {
var selNum = sels.indexOf(firstSelector);
for (var i = selNum; i < sels.length; i++)
{
$(sels[i]).find('.option').remove();
}
};
var populateNextSelect = function(neededObject, targetSelector) {
removeFromNextSelects(targetSelector);
for (var key in neededObject)
{
var name;
neededObject[key].name ? name = neededObject[key].name : name = neededObject[key];
$(targetSelector).append(optionTemplate);
$('.newOption').val(key).html(name).removeClass('newOption').addClass('option');
}
};
var obj1 = {}, obj2 = {}, obj3 = {};
var sels = ["#clothing_sex", "#clothing_kind", "#clothing_size"];
$('#category_group').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[0]);
return;
}
obj1 = {};
var selection = $(this).val();
obj1 = clothes[selection];
populateNextSelect(obj1, sels[0]);
});
$('#clothing_sex').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[1]);
return;
}
obj2 = {};
var selection = $(this).val();
obj2 = obj1[selection].types;
populateNextSelect(obj2, sels[1]);
});
$('#clothing_kind').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[2]);
return;
}
obj3 = {};
var selection = $(this).val();
var arr = obj2[selection].sizes;
for (var i = 0; i < arr.length; i++)
{
obj3[Object.keys(arr[i])[0]] = arr[i][Object.keys(arr[i])[0]];
}
populateNextSelect(obj3, sels[2]);
});
});
Here's the fiddle

selected value not appear in select option in html

I create option dynamically. I bind the all values but when I select value from dropdown menu it not display in the combo box.
help me how to fix this. thanks in advance
HTML:
<select name= "cityNameOption" id = "cityNameOption" >
<option value="0">All</option></select>
js:
// cityList = [{"id":3,"name":"Hospitals"},{"id":1,"name":"Hotels"},{"id":2,"name":"Shopping Mall"}];
var cityObject = jQuery.parseJSON(cityList);
var cityOptions = document.getElementById("cityNameOption");
for ( var i = 1; i <= cityObject.length; i++) {
cityOptions.options[i] = new Option(cityObject[i - 1].name, cityObject[i - 1].id);
}
Try this:
<select name= "cityNameOption" id = "cityNameOption" >
<option value="0">All</option>
</select>
<script type="text/javascript">
//warning 1: js-code must be after HTML
//warning 2: JSON-object must be as a string;
var cityList = '[{"id":3,"name":"Hospitals"},{"id":1,"name":"Hotels"},{"id":2,"name":"Shopping Mall"}]';
var cityObject = $.parseJSON(cityList);
for ( var i = 1; i <= cityObject.length; i++) {
$("#cityNameOption").append('<option value='+cityObject[i - 1].id+'>'+cityObject[i - 1].name+'</option>');
}
</script>

Categories

Resources