Create new select when somebody click in the option - javascript

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>

Related

Need to select text of selected dropdown using JavaScript

I have a dropdown with values. I have an array array with a list of values that will match the drop down values. If the value of text option of the dropdown exists in the array, it shouldn't show in the dropdown as an option. I am stuck on the approach I should use. This is what I have so far.
HTML
Car Plates:
<select title='car/id' id='car_x0020_Plate_x002f'>
<option selected="selected" value="0">none</option>
<option value="16">233-jj2</option>
<option value="10">934-zxy</option>
<option value="90">330-nbh</option>
<option value="11">930-orj</option>
</select>
JavaScript
var hideOption = ['233-jj2', '330-nbh']
var e = document.querySelector([id^='car']);
var strUser = e.value;
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;
for (var x=0; x<hideOption.length; x++){
if (hideOption[x] === strUser){
//remove from dropdown
}
}
I made your idea in a very simple way, if you have any question please tell me
var hideOption = ['233-jj2', '330-nbh'],
select = document.getElementById("select");
for (let i = 0; i < hideOption.length; i = i + 1) {
for (let t = 1; t < select.options.length; t = t + 1) {
if (hideOption[i] == select.options[t].textContent) {
select.options[t].remove();
}
}
}
Car Plates:
<select title='car/id' id='select'>
<option selected="selected" value="0">none</option>
<option value="16">233-jj2</option>
<option value="10">934-zxy</option>
<option value="90">330-nbh</option>
<option value="11">930-orj</option>
</select>
// remove from dropdown
use this code to remove from dropdown
e.removeChild(e.options[e.selectedIndex])
you can use this also
e.selectedOptions[0].remove()
var hideOption = ['233-jj2', '330-nbh']
var e = document.querySelector("[id^='car']");
var selTextArr = Array.from(e.options).map(option => option.text)
for (var x=0; x<selTextArr.length; x++){
if (hideOption.includes(selTextArr[x])){
e.remove(x)
}
}
Car Plates:
<select title='car/id' id='car_x0020_Plate_x002f'>
<option selected="selected" value="0">none</option>
<option value="16">233-jj2</option>
<option value="10">934-zxy</option>
<option value="90">330-nbh</option>
<option value="11">930-orj</option>
</select>
var options = document.querySelector("[id^='car']").children;
var hideOption = ['233-jj2', '330-nbh']
for (var i = 0; i < options.length; i++){
if(hideOption.indexOf(options[i].text) > -1){
options[i].remove();
}
}

disabled and selected is not working in customize select option menu (Javascript)

I have customized select option menu by JavaScript but there is a problem, this code is not working when option tag is disabled or selected as true.
I want this solution by JavaScript.
<form class="wrapper" action="index.html">
<ul>
<li>
<div class="magneto-combobox">
<select class="combo-box" data-element="combobox">
<option value="apple" disabled>apple</option>
<option value="mango">mango<option>
<option value="banana" >banana<option>
</select>
</div>
</li>
<lil>
<input type="submit" value="submit"/>
</lil>
</ul>
</form>
<script>
var select = document.getElementsByTagName('select');
var customselect = [];
var menu = [];
var items = [];
for(var i = 0 ; i < select.length ; i++) {
if(select[i].getAttribute("data-element") == "combobox") {
option = select[i].getElementsByTagName('option');
menu[i] = document.createElement('ul');
customselect[i] = document.createElement('div');
customselect[i].className = select[i].className;
select[i].parentNode.appendChild(customselect[i]);
select[i].parentNode.appendChild(menu[i]);
for(var j = 0 ; j < option.length; j++) {
items[j] = document.createElement('li');
menu[i].appendChild(items[j]);
menu[i].childNodes[j].innerText = option[j].value;
menu[i].previousSibling.innerText = option[0].value;
option[j].selected = true;
if(!select[i].getAttribute('disabled')) {
items[j].onmousedown = itemSelected;
}
}
}
}
function itemSelected() {
var prevsibling = this.parentNode.previousSibling;
var firstchild = this.parentNode.parentNode.firstChild;
var option = firstchild.getElementsByTagName('option');
prevsibling.innerText = this.innerText;
firstchild.value = prevsibling.innerText;
document.getElementById('demo').innerText = firstchild.value;
}
</script>
Your <option> tags are not correctly closed with a matching </option> tag.
You code should be:
<option value="apple" disabled>apple</option>
<option value="mango">mango</option>
<option value="banana">banana</option>

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

assign value to dropdown using 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 !!!

Categories

Resources