move option from one select to another select with JS - javascript

From two html selects, I would like to move when I click the button to move an option to another select with javascript vanila, and when it has been moved, it is removed from the select from where it was at the beginning. It should also work the other way around.
function move1() {
var x = document.getElementById("select1");
}
function move2() {}
<select id="select1">
<option value="0">1</option>
<option value="0">2</option>
<option value="0">3</option>
</select>
<button type="button" onclick="move1()">>></button>
<button type="button" onclick="move2()"><<</button>
<select id="select2"></select>

You can do it like this:
Fetch both selects with getElementById() and store them in select_1 and select_2 variables.
Check if selected option exists by compering selectedIndex property of the select with -1. It will be equal to -1 only if the user didn't select anything.
If selectedIndex is equal to -1, then do nothing because there is nothing to transfer to second select.
If selectedIndex is different from -1, it means that user selected something and option with that index should be transfered.
Create new option for second select with document.createElement('option') and copy the selected option values to the new option.
Remove the selected option of current select with select.options.remove(select.selectedIndex)
function move1() {
const select_1 = document.getElementById("select1");
const select_2 = document.getElementById("select2");
if(select_1.selectedIndex !== -1) {
const selected_option = select_1.options[select_1.selectedIndex];
let new_option = document.createElement('option');
new_option.value = selected_option.value
new_option.innerHTML = selected_option.innerHTML;
select_2.appendChild(new_option);
select_1.options.remove(select_1.selectedIndex)
}
}
function move2(){
const select_1 = document.getElementById("select1");
const select_2 = document.getElementById("select2");
if(select_2.selectedIndex !== -1) {
const selected_option = select_2.options[select_2.selectedIndex];
let new_option = document.createElement('option');
new_option.value = selected_option.value
new_option.innerHTML = selected_option.innerHTML;
select_1.appendChild(new_option);
select_2.options.remove(select_2.selectedIndex)
}
}
<select id="select1">
<option value="0">1</option>
<option value="0">2</option>
<option value="0">3</option>
</select>
<button type="button" onclick="move1()">>></button>
<button type="button" onclick="move2()"><<</button>
<select id="select2"></select>

Here's a version that can manage more than 2 sets of <select> and <button> pairs. If there are more than 2 pairs, all recieving <select> will add the selcted <option>. In the HTML a data-* attribute is added to each <option>:
<option data-idx="0" value='1'>1</option>
<option data-idx='1' value="2">2</option>
<option data-idx='2' value="3">3</option>
The value of data-idx is the <option>s original index position. In the event handler switchOPt(e) the data-idx value will be used to determine what index it should be placed in:
to.add(copy, +copy.dataset.idx);
All details are commented in the example.
/*
Collect all buttons into a HTMLCollection then convert it
into an Array. Same with all select
*/
const btnArray = [...document.querySelectorAll('button')];
const selArray = [...document.querySelectorAll('select')];
/*
Iterate through the array of buttons. Register each button
to the click event. The event handler is switchOpt(e)
*/
btnArray.forEach(btn => btn.addEventListener('click', switchOpt));
// Event handler always passes the Event Object
function switchOpt(e) {
/*
Determine the select that will send it's option by
matching it's #id vs this.name (the [name] of the button
the user clicked
*/
const from = document.getElementById(this.name);
// if the select doesn't have any options end function
if (from.childElementCount < 1) return;
/*
Determine the select that adds an option by .filter()
under the condition that it is NOT >from<
*/
let to = selArray.filter(sel => sel.id != from.id);
// Rereference >to< to be the select with the array
to = to[0];
// Determine which option has been selected
const opt = from.options[from.selectedIndex];
// Make a copy of the selected option
const copy = opt.cloneNode(true);
/*
Add >copy< to >to< the second parameter is the index
of the element that >copy< will be placed before it so
it'll always be in order
*/
to.add(copy, +copy.dataset.idx);
// Remove the option from >from<
opt.remove();
}
<!-- Assign each option a data attribute wuth the value
of it's index -->
<select id="A">
<option data-idx='0' value="1">1</option>
<option data-idx='1' value="2">2</option>
<option data-idx='2' value="3">3</option>
</select>
<button name='A' type="button">>></button>
<button name='B' type="button"><<</button>
<select id="B"></select>

Related

Two Drop Down Menus

I wish I could use jQuery, but this has to in JavaScript. I'd appreciate the help.
When "empty" (first drop down menu) is selected, I need all values from the second drop down menu (a, b, c).
When "1" is selected, I need just a, b.
When "2" is selected, I need just b, c.
Nothing's wrong with the drop down menu. Just had to change the values. How would I fix this in JavaScript?
First menu
<onchange="first(this);>
<option value="empty"></option>
<option value="1">1</option>
<option value="2">2</option>
Second menu
<id="second">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
One solution that I would prefer is to set the style to none via CSS in JS. This way, the element still exists but it is just hidden from the viewer.
You can the get value of an element via [element-here].value and compare the to some value that you want. From there, you would select the second drop down option value you have and run [element-here].style.display = "none"
Another way that is more complicated that I would not recommend is to create and destroy elements entirely. Something like:
var x = document.createElement("option");
x.value = VALUE HERE;
parent.appendChild(document.createTextNode("TEXT HERE"))
This is a bit sloppy, but here's one way to do it. You have an array of data with the valid secondary values per primary value. Then you render them each time the primary list changes.
let dropdownlist = [];
dropdownlist[1] = ['a', 'b', 'c'];
dropdownlist[2] = ['b', 'c'];
let select = document.createElement('select');
document.getElementById('myItemList').appendChild(select);
let x = 1;
document.getElementById('firstddl').addEventListener('change', (e) => {
//console.log(e.target.value);
x = e.target.value;
select.innerHTML = '';
renderDDL(dropdownlist, x)
});
function renderDDL(dropdownlist, x) {
dropdownlist[x].forEach(function(item) {
let option = document.createElement('option');
select.appendChild(option);
option.innerHTML += item;
});
}
renderDDL(dropdownlist, x); // Runs once
<select id="firstddl">
<option value=1>1</option>
<option value=2>2</option>
</select>
<div id="myItemList">
</div>

Slicing elements from three select menus into and out of array

var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
var array = [];
let sel1 = false;
function myFunct1() {
var one = select1.options[select1.selectedIndex].value;
if(array.length === 1 && !sel1) array.unshift(one);
else array.splice(0,1,one);
console.log(array);
sel1 = true;
}
function myFunct2() {
var two = select2.options[select2.selectedIndex].value;
array.splice(sel1, 1, two);
console.log(array);
}
function myFunct3() {
var three = select3.options[select3.selectedIndex].value;
}
<select id = 'select1' onchange = 'myFunct1()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog1'>Dog</option>
<option value = 'Cat1'>Cat</option>
<option value = 'Bear1'>Bear</option>
</select>
<select id = 'select2' onchange = 'myFunct2()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog2'>Dog</option>
<option value = 'Cat2'>Cat</option>
<option value = 'Bear2'>Bear</option>
</select>
<select id = 'select3' onchange = 'myFunct3()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog3'>Dog</option>
<option value = 'Cat3'>Cat</option>
<option value = 'Bear3'>Bear</option>
</select>
I have this method that works exactly how I want it with two select menus. So if you select twice in a row from the second select the array's length is never more than one until you select from the first. Now I want to incorporate a third select menu. Please help me make this work. I'm aware I could combine them all into one function and not have to deal with these issues but for my use, I can't do that. The main condition is that there is never multiple selections within the array from the same select menu and never any empty positions within the array that still count towards its length. so an array of [undefined, Cat2] does not occur.
The simple way is:
Create two arrays i.e realArr(to keep strings at original indexes). For example value from select1 will always we set to realArr[0] and from select2 to realArr[1]...
Second array showArr is array from which you will remove undefined using filter()
var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
var select3= document.getElementById('select3');
var realArr = [];
var showArr = [];
function myFunct1() {
var one = select1.options[select1.selectedIndex].value;
realArr[0] = one;
showArr = realArr.filter(x => x !== undefined);
console.log(showArr);
}
function myFunct2() {
var two = select2.options[select2.selectedIndex].value;
realArr[1] = two
showArr = realArr.filter(x => x !== undefined);
console.log(showArr);
}
function myFunct3() {
var three = select3.options[select3.selectedIndex].value;
realArr[2] = three;
showArr = realArr.filter(x => x !== undefined);
console.log(showArr);
}
<select id = 'select1' onchange = 'myFunct1()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog1'>Dog</option>
<option value = 'Cat1'>Cat</option>
<option value = 'Bear1'>Bear</option>
</select>
<select id = 'select2' onchange = 'myFunct2()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog2'>Dog</option>
<option value = 'Cat2'>Cat</option>
<option value = 'Bear2'>Bear</option>
</select>
<select id = 'select3' onchange = 'myFunct3()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog3'>Dog</option>
<option value = 'Cat3'>Cat</option>
<option value = 'Bear3'>Bear</option>
</select>

Multiselect element identifying after multiple clicks [duplicate]

This question already has answers here:
How to get all selected values of a multiple select box?
(28 answers)
Closed 6 years ago.
I've select element box with multiple options.
A
B
C
D
It also has "multiple" attribute, allowing user to choose multiple options at once (ctrl + click).
Currently I'm using
var example= document.getElementById('selectedboxid');
which returns selected element id (what is what I need!).
Problem I am facing is - if user wants to choose multiple elements, getElementById will return same id (the one, who was clicked first!). I need to return newly clicked element id on every click (choosing more than one element at once). How can this be accomplished?
Code looks like:
var example = document.getElementById('select_example');
select_example.addEventListener('change', function() {
var elementID = select_example.value; // Element ID stays the same...
...
}
});
This should work for getting the last one clicked and also grabbing the full list.
var sel = document.getElementById('sel');
// GEt all selected
sel.addEventListener('change',function() {
console.log(this.selectedOptions);
});
// Get the one clicked
sel.addEventListener('click', function(evt) {
console.log(evt.target);
});
select {
width: 200px;
height: 200px;
}
<select id="sel" multiple>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Yout can do it like this:
var selectedOptions = document.querySelectorAll('#select_example option:checked')
This will return NodeList of all selected option elements
var selectedValues = Array.prototype.map.call(selectedOptions, function(el){return el.value})
This will map array of selected option elements to array of selected values.
Use selectedOptions property. Example:
<select id="myselect" multiple="multiple">
<option value="0">0-0-0-0-0-0</option>
<option value="1">1-1-1-1-1-1</option>
<option value="2">2-2-2-2-2-2</option>
<option value="3">3-3-3-3-3-3</option>
<option value="4">4-4-4-4-4-4</option>
</select>
var select = document.getElementById('myselect');
function processChange(event) {
var selectElement = event.target;
console.log(selectElement.selectedOptions);
}
select.addEventListener('change', processChange);
Working example: https://jsfiddle.net/a8nbj7rw/

How to fill and add text in a text field with drop down selections

I'm not a coder ut I've found this code here
http://jsfiddle.net/kjy112/kchRh/
<textarea id="mytext"></textarea>
<select id="dropdown">
<option value="">None</option>
<option value="text1">text1</option>
<option value="text2">text2</option>
<option value="text3">text3</option>
<option value="text4">text4</option>
</select>
var mytextbox = document.getElementById('mytext');
var mydropdown = document.getElementById('dropdown');
mydropdown.onchange = function(){
mytextbox.value = mytextbox.value + this.value;
}
I'd like to modify it so that I've more than one dropdown and each one add his text in the same field.
Practically I'd have to create a compact code easily for the user so that the user select some phrases using the dropdown and the code will fill the text field.
If I can be more precise please let me know. As said Iìm not a coder so if you can write down the code to use I'll be very happy.
Thanks!
Here's a js bin with multiple dropdowns' onchange event being listed to: https://jsfiddle.net/kchRh/944/
You want to give the dropdowns class names and then loop through each drop down to setup their listeners.
HTML:
<textarea id="mytext"></textarea>
<select class="dropdown">
<option value="">None</option>
<option value="text1">text1</option>
<option value="text2">text2</option>
<option value="text3">text3</option>
<option value="text4">text4</option>
</select>
<select class="dropdown">
<option value="">2None</option>
<option value="2text1">2text1</option>
<option value="2text2">2text2</option>
<option value="2text3">2text3</option>
<option value="2text4">2text4</option>
</select>
JS:
var mytextbox = document.getElementById('mytext');
var mydropdowns = document.getElementsByClassName('dropdown');
for(i=0;i<mydropdowns.length;i++) {
mydropdowns[i].onchange = function(){
mytextbox.value = mytextbox.value + this.value;
}
}
I'd suggest the following approach:
// create a reusable function:
function updateTextArea() {
// get all the elements with the class 'dropdown':
var selectElems = document.querySelectorAll('.dropdown'),
// get the <textarea> element, using its id:
textArea = document.getElementById('mytext'),
// using Array.prototype.filter on the array-like
// NodeList, using Function.prototype.call, in
// order to iterate over the found '.dropdown'
// elements to form an array of only those elements
// with a non-zero-length value:
values = Array.prototype.filter.call(selectElems, function(el) {
if (el.value.trim().length) {
return el.value;
}
// iterating over the filter-created array, to form a map of
// the selected values of the elements:
}).map(function(el) {
return el.value;
// joining those arrays together, with Array.prototype.join,
// to form a comma-separated string of values, and appending
// a period:
}).join(', ') + '.';
// setting the value of the <textarea> to:
// - an empty string (if the values variable is
// just the appended-period), or to the value of
// the values variable:
textArea.value = values === '.' ? '' : values;
}
// as above, retrieving the '.dropdown' elements:
var selects = document.querySelectorAll('.dropdown');
// iterating over the '.dropdown' elements, using
// Array.prototype.forEach:
Array.prototype.forEach.call(selects, function(el, index, arr) {
// within the anonymous function of Array.prototype.foreach:
// the first argument (here: 'el') is the current array-element,
// second argument (here: 'index') is the index of the current
// array-element within the array over which we're iterating,
// third argument (here: 'arr') is the array over which we're
// iterating.
// binding updateTextArea as the change event-handler for
// each of the array-elements over which we iterate:
el.addEventListener('change', updateTextArea);
});
function updateTextArea() {
var selectElems = document.querySelectorAll('.dropdown'),
textArea = document.getElementById('mytext'),
values = Array.prototype.filter.call(selectElems, function(el) {
if (el.value.trim().length) {
return el.value;
}
}).map(function(el) {
return el.value;
}).join(', ') + '.';
textArea.value = values === '.' ? '' : values;
}
var selects = document.querySelectorAll('.dropdown');
Array.prototype.forEach.call(selects, function(el) {
el.addEventListener('change', updateTextArea);
});
<textarea id="mytext"></textarea>
<select class="dropdown">
<option value="">None</option>
<option value="text1">text1</option>
<option value="text2">text2</option>
<option value="text3">text3</option>
<option value="text4">text4</option>
</select>
<select class="dropdown">
<option value="">None</option>
<option value="text5">text5</option>
<option value="text6">text6</option>
<option value="text7">text7</option>
<option value="text8">text8</option>
</select>
JS Fiddle demo.
Note, in the HTML, I've changed from the use of id to identify the <select> elements, to using class; simply because it allows a group of elements to be associated together without having to use a large number of ids and subsequently having to update the JavaScript in turn with the HTML.
Referencs:
Array.prototype.filter().
Array.prototype.forEach().
Array.prototype.join().
Array.prototype.map().
document.querySelectorAll().
eventTarget.addEventListener().
Function.prototype.call().

Accessing several form options

How do I access several option values in a form, under two different select ids, with JavaScript?
Here's the code: (JSFiddle: http://jsfiddle.net/sebastianonline/9yL4rv6j/)
(HTML5)
Select your favorite fruit:
<select id="mySelect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
Click the button to return the value of the selected fruit.
Pick a product
Amount
<label><strong>Amount:</strong></label>
<select id="amount">
<option selected>1</option>
<option>2</option>
<option>3</option>
</select>
<!-- text value here -->
<p id="include"></p>
<p id="include2"></p>
(JavaScript)
function mySelect()
{
var x = document.getElementById("mySelect").selectedIndex;
var p = document.getElementsByTagName("option")[x].value;
document.getElementById("include").innerHTML = p;
}
function myAmount()
{
var a = document.getElementById("amount").selectedIndex;
var b = document.getElementsByTagName("option")[a].value;
document.getElementById("include2").innerHTML = b;
}
Function mySelect() is able to pick the right option value and insert it in the first paragraph, however, the second function (myAmount()) is picking the same options as the first function, even though its id points to select id="amount". I need the second function to pick the options in select id="amount" and print it in p id="include2".
You are using document.getElementsByTagName("option"), which returns all option elements in the document, not all options for the current select. Which of course means your indexing is out.
But you can get the selected option's value in a given select element using the .value property of the select element itself:
function mySelect() {
var x = document.getElementById("mySelect").value;
document.getElementById("include").innerHTML = x;
}
function myAmount() {
document.getElementById("include2").innerHTML =
document.getElementById("amount").value;
}

Categories