I have a form and I wish that second select option depends on first. It means if I select DEV_1_OLD otption it wont be showed in the second select list. How to do it with JS?
I started something like that but it doesnt work as I expected
<select id="s11" name="source" onchange="preapreSelectOptions()">
<option value="DEV_1_OLD">DEV_1_OLD</option>
<option value="TEST_OLD">TEST_OLD</option>
<option value="PROD_OLD">PROD_OLD</option>
</select>
Target Environment:
<select id="s12" name="target" required>
</select>
<script>
function preapreSelectOptions () {
var op = document.getElementById("s11").getElementsByTagName("option");
console.log(op.length);
var opClone = op;
for (var i = 0; i < op.length; i++) {
opClone[i] = document.createElement('option');
// opClone[i].textContent = op[i].value;
// opClone[i].value = op[i].value;
document.getElementById('s12').appendChild(opClone[i]);
}
}
</script>
you need to add a condition to check if the option you appending is the selected one
<select id="s11" name="source" onchange="preapreSelectOptions()">
<option value="DEV_1_OLD">DEV_1_OLD</option>
<option value="TEST_OLD">TEST_OLD</option>
<option value="PROD_OLD">PROD_OLD</option>
</select>
Target Environment:
<select id="s12" name="target" required>
</select>
<script>
function preapreSelectOptions () {
var op = document.getElementById("s11").getElementsByTagName("option");
var selected = document.getElementById("s11")
for (var i = 0; i < op.length; i++) {
// check if option is not selected
if(op[i].value != selected.options[selected.selectedIndex].value) {
o = document.createElement('option')
o.value = op[i].value
o.text = op[i].text
document.getElementById('s12').appendChild(o);
}
}
}
</script>
A little improvement for your code so you can dynamically generate the next option list:
Add conditional checking if value not selected
Make the function preapreSelectOptions accept argument so you can automatically generate new list for next select element based on current selection.
When call the preapreSelectOptions function, pass the current element id and next element id.
//Make it accept argument so you can automatically generate new list for next select
function preapreSelectOptions(currentSelectedElement, nextSelectElementId){
let selectedValue = document.getElementById(currentSelectedElement).value
//list the remain value in case you need it for other logic
let remainValue = function(){
let selectOptionList = document.getElementById(currentSelectedElement).children
let arr = []
for(var i = 0; i < selectOptionList.length; i++){
if(selectOptionList[i]["value"] !== selectedValue){
arr.push(selectOptionList[i]["value"])
}
}
return arr
}()
//generate option
for(var i = 0; i < remainValue.length; i++){
let newOption = document.createElement("option")
newOption.value = remainValue[i]
newOption.textContent = remainValue[i]
document.getElementById(nextSelectElementId).appendChild(newOption)
}
}
s11<br>
<select id="s11" name="source" onchange="preapreSelectOptions('s11','s12')" value="">
<option value=""></option>
<option value="DEV_1_OLD">DEV_1_OLD</option>
<option value="TEST_OLD">TEST_OLD</option>
<option value="PROD_OLD">PROD_OLD</option>
<option value="PROD_NEW">PROD_NEW</option>
<option value="PROD_LATEST">PROD_LATEST</option>
</select>
<br>
s12<br>
<select id="s12" name="source" onchange="preapreSelectOptions('s12','s13')">
</select>
<br>
s13<br>
<select id="s13" name="source">
</select>
Related
this is the javascript function that I have
function GetUserAddress() {
var address = '<%= Session["addressmap"].ToString() %>';
return address;
}
I want to set the value for this dropdown list below to whatever address this function returns
<select id="end">
<option value="" >Select Value</option>
<option value="GetUserAddress()" ></option>
</select>
Considering your address variable returns an Array, you can do something like this in plain JS to create custom options.
jsfiddle DEMO : jsfiddle
<select id="end">
<option value="" >Select Value</option>
</select>
<script>
(function() {
var address = ['USA','Australia'];
var select = document.getElementById("end");
for (var i = 0; i < address.length; i++) {
var option = document.createElement("option");
option.setAttribute("value", address[i]);
option.text = address[i];
select.appendChild(option);
}
})();
</script>
This is just to give you an idea of how you can achieve dynamic operations.
<select name="List" id="List">
<option value="">-Select-</option>
<option value="">--Product--</option>
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
<option value="">--Software--</option>
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
<option value="">--Services--</option>
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</select>
I have the above List on my HTML select field.
I want to be able to get only the values --Product--, --Software--, --Services--
So I created an loop to go throw the list of products and used the method startwith to pickup the values starting with "--".
function loadFilter() {
var x = document.getElementById('List');
var i;
var n;
for (i = 0; i < x.length; i++) {
str = x[i].text
var n = str.startsWith('--');
flag = true;
if (n == true) {
alert(x[i].text); // list --Product--, --Software--, --Services--
alert(x[3].text); // prints from the LIST <product1> and not <--Services-->
}
}
}
So when the flag is true, the alert(x[i].text); list correctly the values (--Product--, --Software--, --Services--).
But when I try to get them by their values(index), E.G ..I need to get only (--Services--), so I use x[3].text), but this returns me the whole List values >> and not <--Services-->.
You can use the below code to populate array arr with the list of options having "--".
Then you can use arr[2] to get --Services--.
var arr = [];
[].slice.call(document.querySelectorAll("#List option")).map(function(el){
if (el.text.indexOf("--") === 0) arr.push(el.text);
});
console.log(arr)
console.log(arr[2])
<select name="List" id="List">
<option value="">-Select-</option>
<option value="">--Product--</option>
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
<option value="">--Software--</option>
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
<option value="">--Services--</option>
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</select>
Here you go:
function loadFilter() {
var element = document.getElementById('List');
var children = element.children;
var filtered = [];
for (var i = 0; i < children.length; i++) {
if (children[i].textContent.startsWith('--')) {
filtered.push(children[i].textContent);
}
}
return filtered;
}
To recap what the function did:
Get the element "List"
Get the children of "List"
Create an array to hold elements that pass the filter
Go through each element and add those with match the specified regex
Return the elements that pass the filter
I'm still not entirely sure what you're trying to do. --Services-- is index 9, not 3. To get --Services-- you need x[9].text
If you want to rearrange the three --xx-- into their own index, you need to push them into a new array, like so:
var output = []
if (n === true) output.push(x[i].text)
console.log(output[2]) // --Services--
You can use simple forEach loop to loop through elements like here, but first you need to create Array from your DOM Node list:
var list = Array.from(x);
list.forEach((value,index)=>{
if (value.text.startsWith('--')){
alert(value.text);
}
});
I've put it up on fiddle so you can check:
https://jsfiddle.net/pegla/qokwarcy/
First of all, you don't seen to be using your flag at all.
If I understood it correctly, you are trying to get --Services-- using x[3].text, but if you count your whole list the element at index [3] is the . You can verify that with the code bellow:
f (n == true) {
alert('index '+ i + ': ' + x[i].text); // list --Product--, --Software--, --Services--
}
You could create a new array containing the filtered options and then access the with the known index:
var filteredArray = [];
f (n == true) {
filteredArray.push(x[i]); //insert the element in the new array.
}
alert(filteredArray[2].text) //print --Service--, the third element of filtered array.
Remember that javascript has zero indexed array, so the first element has index 0, so, in order to acces the third element you'll need the index 2.
May be you want to try using optgroups?
Something like this:
<select name="List" id="List">
<option value="">-Select-</option>
<optgroup label="--Product--">
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
</optgroup>
<optgroup label="--Software--">
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
</optgroup>
<optgroup label="--Services--">
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</optgroup>
</select>
Then,
var select = document.getElementById('List');
var optgroups = select.getElementsByTagName('optgroup');
console.log(optgroups[2].label);
Will show:
--Services--
try:
function load() {
list = document.getElementById('List');
var data = document.getElementsByTagName('option');
currentCatagory=null;//the current selected catagory
currentvalue=null;
listdata=[];
//for all the options
for(cnt = 0; cnt < data.length; cnt++){
var e = data[cnt].innerHTML;//get option text
if(e.startsWith('-')){//test to make a catagory out of it
if(currentCatagory!=null)//do not concat is listdata is null
listdata=listdata.concat(currentCatagory);
currentCatagory = {"this":e,"listOfItems":[]};//create the catagory
}else if(currentCatagory!=null){//make sure currentCatagory is not null
var l=currentCatagory.listOfItems;//get the Catagory's list
currentCatagory.listOfItems = l.concat(e);//and add e
}
}
listdata=listdata.concat(currentCatagory);//add last catagory
//sets the list to show only catagories
var inner='';
for (i = 0; i < listdata.length; i++) {
inner+=parseOp(listdata[i].this);
}
list.innerHTML=inner;
}
function update(){
//check to make sure everything is loaded
if(typeof list=='undefined'){
load();
}
var inner='';//the new options
var value=list.options[list.selectedIndex].innerHTML;
if(value==currentvalue) return;
if(value.startsWith('-')){//if catagory
if(value.startsWith('--')){//if not -Select-
for (i = 0; i < listdata.length; i++) {//for all catagories
if(value==listdata[i].this){//if it is the current selected catagory then...
currentCatagory=listdata[i];//update the currentCatagory object
inner+=parseOp(listdata[i].this);//parse as option and append
//then append catagory's items
for(item in listdata[i].listOfItems){
inner+=parseOp(listdata[i].listOfItems[item]);
}
}else{//appends the other catagories
inner+=parseOp(listdata[i].this);
}
}
}else{//if it is '-select-' then just append the catagories
for (i = 0; i < listdata.length; i++) {
inner+=parseOp(listdata[i].this);
}
}
//set the new options
list.innerHTML=inner;
}
}
function parseOp(str){
//parse the options
return '<option value="">'+str+'</option>';
}
<select name="List" id="List" onchange="update();">
<option value="">-Select-</option>
<option value="">--Product--</option>
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
<option value="">--Software--</option>
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
<option value="">--Services--</option>
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</select>
and to set the dropdown box you will have to run load() otherwise load() will only be called after the first change event occurs.
I have a select dropdown list and a multiselect dropdown. And i want the multiselect one to be depended on the select one. How can i do it?
<div class="row">
<div class="col" ><label>Which class: </label><select name="type_of_subject_c" id="type_of_subject_c" tabindex="1">
<option value="" selected="selected">--не выбрано--</option>
<option value="5">5th </option>
<option value="6">6th</option>
<option value="7">7th</option>
<option value="8">8th</option>
</select>
</div>
And i want, for example, if a person chose 5th - show in the multiselect field such options as "Math", "English", "Literature"
If a person chose 6th - show "Math", "Science", "Music"
etc.
<div class="row">
<div class="col"><label>Coruses: </label><select name="course_subj_c[]" id="course_subj_c" multiple="multiple" tabindex="1" >
<option value="math">Math</option>
<option value="eng>English</option>
<option value="lit">Literature</option>
First of all you should always add code to your question even if it is not working. Stackoverflow is a place to learn, how can we help you if you don't share your work.
Array data contains all your data. We add options to both selects dynamically.
Function init() is where it starts. To change the data we need to add an event listener to our second select like so
select1.addEventListener('change', function(e) ...
Here is working example. Please read my comments to have better understanding. If you have any questions don't hesitate to ask.
var data = [
{ subject : 'one',
selected: true,
courses: ['Math_one', 'English_one', 'Literature_one']
},
{ subject : 'two',
courses: ['Math_two', 'English_two', 'Literature_two']
},
{ subject : 'three',
courses: ['Math_three', 'English_three', 'Literature_three']
},
{ subject : 'four',
courses: ['Math_four', 'English_four', 'Literature_four']
},
{ subject : 'five',
courses: ['Math_five', 'English_five', 'Literature_five']
},
{ subject : 'six',
courses: ['Math_six', 'English_five', 'Literature_six']
}
];
var select1 = document.getElementById('type_of_subject_c');
var select2 = document.getElementById('course_subj_c');
var resultText = document.getElementById('currentlySelected');
// Your result, do whatever you want
var selectedOptions = [];
function init(data) {
var subjects = [];
for (var i = 0; i < data.length; i++) {
var element = data[i];
// Add subjects to subjects array
subjects.push(element.subject);
// We skip if current element is not selected
if (!element.selected) {
continue;
}
// If element is selected we change content of `select2`
if (element.selected) {
fillSelectOptions(select2, element.courses);
}
}
// Append all subjects as select options to `select1`
fillSelectOptions(select1, subjects);
}
// Lets add event listener `onChange` to `select`
select1.addEventListener('change', function(e) {
// Based on selected/current value we will change data options of `select2`
var selectedValue = e.target.value;
// Clear result text each time we change `select1`
resultText.innerHTML = '';
selectedOptions = [];
// Before we append new data lets clear old one
clearSelect2Options();
// Lets find related data to selected/current value
for (var i = 0; i < data.length; i++) {
var element = data[i];
if (element.subject === selectedValue) {
fillSelectOptions(select2, element.courses);
break;
}
}
});
select2.addEventListener('change', function(e) {
var options = document.querySelectorAll('#course_subj_c option');
resultText.innerHTML = '';
selectedOptions = [];
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.selected) {
selectedOptions.push(option.value);
}
}
// Our Result is :
//console.log(selectedOptions);
// Append result to `resultText` convert array to string via `join()`
resultText.innerHTML = selectedOptions.join();
});
function fillSelectOptions(selector, dataOptions) {
for(var i = 0; i < dataOptions.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = dataOptions[i];
opt.value = dataOptions[i];
selector.appendChild(opt);
}
}
function clearSelect2Options() {
var i;
for(i = select2.options.length - 1 ; i >= 0 ; i--) {
select2.remove(i);
}
}
init(data);
favorite
<select id="type_of_subject_c" name="type_of_subject_c">
</select>
<select name="course_subj_c[]" id="course_subj_c" multiple="multiple" tabindex="1">
</select>
<div>Currently selected <span id="currentlySelected"></span></div>
You can't achieve this just using HTML.
You need to use JavaScript in order to populate the other dropdown with elements depending on the value chose in the first dropdown.
Add an onchange event to the first dropdown.
Inside this function, clear all the option elements of the second dropdown. Then depending on the selected value of the first dropdown, fill the second one. Here an example of code using jQuery.
<select name="first-dropdown" id="first-dropdown" onchange="processValue();">
<option value="" selected="selected">Default Option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="second-dropdown" multiple="multiple" id="second-dropdown">
<option value="" selected="selected">Select option in the first dropdown</option>
</select>
<script type="text/javascript">
function processValue() {
var firstChoice = $('#first-dropdown').val();
// ensure you didn't select the default option
if (firstChoice !== "") {
$('#second-dropdown').empty();
switch (firstChoice) {
case "1":
$('#second-dropdown').append('<option value="first1">First 1</option>');
$('#second-dropdown').append('<option value="first2">First 2</option>');
break;
case "2":
$('#second-dropdown').append('<option value="second1">Second 1</option>');
$('#second-dropdown').append('<option value="second2">Second 2</option>');
break;
// ... other cases
default:
break;
}
// init jquery checkbox plugin again
$('#second-dropdown').multipleSelect();
}
}
</script>
Here the link to jsfiddle:
https://jsfiddle.net/37swkpso/
I have 2 dropdown list, where in the first dropdown list i have some data and if I select the data it has to be stored into the second dropdown list. Here is the code :-
This is the first dropdown list,
<select name="weekId" id="weekId" onchange="getSelected(value)">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
This is the second list,
<select id="selectedWeek" name="selectedWeek" size="5" multiple="multiple">
If I select Weekly in the first dropdown, the value has to get stored in the second dropdown. How do I go about implementing this?
Thanks in advance!!
var weekId = document.getElementById('weekId')
, selectedWeek = document.getElementById('selectedWeek')
, option;
weekId.onchange = function() {
option = document.createElement('option');
option.value = this.value;
option.text = this.options[this.selectedIndex].text;
selectedWeek.appendChild(option);
weekId.removeChild(this.options[this.selectedIndex]);
};
see working fiddle here: http://jsfiddle.net/bKrFK/1/
the last line in the event-handler will remove the selected option from the weekId select-box (remove that line if not needed)
You can do this using Javascript:
function listbox_moveacross(sourceID, destID) {
var src = document.getElementById(sourceID);
var dest = document.getElementById(destID);
for(var count=0; count < src.options.length; count++) {
if(src.options[count].selected == true) {
var option = src.options[count];
var newOption = document.createElement("option");
newOption.value = option.value;
newOption.text = option.text;
newOption.selected = true;
try {
dest.add(newOption, null); //Standard
src.remove(count, null);
}catch(error) {
dest.add(newOption); // IE only
src.remove(count);
}
count--;
}
}
}
Pass this function with ids of your selectbox.
For Demo: Listbox move left-right options JavaScript
Try this..
<html>
<body>
<select name="weekId" id="weekId" onchange="document.getElementById('selectedWeek').value=this.value">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
<select id="selectedWeek" name="selectedWeek" size="5" multiple="multiple">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
</body>
</html>
Note : Second drop down has all value available in first select box.
First of all, when you call the javascript function in onChange event, replace getSelected(value) to getSelected(this.value).
Now after that,
Your javascript function getSelected(value) should look like this
function getSelected(value)
{
document.getElementById("selectedWeek").innerHTML = '<option value="'+value+'">'+value+'</option>';
}
You could use the following, without any jQuery dependencies.
I've added some comments to explain what is going on.
<script>
function handleSelection(weekDropDown) {
// Get selected value
var selection = weekDropDown.options[weekDropDown.selectedIndex].value;
var selectedWeekDropDown = document.getElementById("selectedWeek");
var opt;
if(selectedWeekDropDown.options[0]) {
// Replace
opt = selectedWeekDropDown.options[0];
} else {
// Add an option
opt = document.createElement("option");
}
if(!selectedWeekDropDown.options[0]) {
selectedWeekDropDown.options.add(opt);
}
// Set the option text and value
opt.text = selection;
opt.value = selection;
}
</script>
<select name="weekId" id="weekId" onchange="handleSelection(this)">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
<select id="selectedWeek" name="selectedWeek" size="5" multiple="multiple">
I am trying to select dropdown automatically based on values from another dropdown. Second dropdown will have more values than first one. If I select the first dropdown, then the second should be selected automatically. I tried the below code and getting error: Options is null or not an object. ???
<script type="text/javascript">
function showState(me){
var values = ''; //populate selected options
for (var i=0; i<me.options.length; i++)
if (me.options[i].selected)
values += me.options[i].value + ',';
values = values.substring(0, values.length-1);
var selected=[values];
var del = document.getElementById('data').value;
for(var i=0; i<del.options.length; i++);
{
if(values[i] == del.options[i])
{
del.options[i].selected;
}
}
}
</script>
<select multiple="multiple" onchange="showState(this);">
<option value="1">Test1</option>
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
<select name="data" id="data" multiple="multiple">
<option value="1">Test1</option>
<option value="2">Test2</option>
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
I think you should make some correction in your code as below :
<script type="text/javascript">
function showState(me){
var values = ''; //populate selected options
for (var i=0; i<me.length; i++)
if (me.options[i].selected)
values += me.options[i].value + ',';
values = values.substring(0, values.length-1);
var selected=[values];
var del = document.getElementById('data');
for(var i=0; i<del.length; i++)
{
for(var j=0;j<values.length;j++)
{
if(values[j] == del.options[i].value)
{
del.options[i].selected = true;
}
}
}
}
</script>
for more details on Select and Option objects in javascript you may refer this link !
I think your problem is here var del = document.getElementById('data').value;. If you want to access the select options, you should use var del = document.getElementById('data');, without the .value. This way the variable del should have the .options array.