Multiselect element identifying after multiple clicks [duplicate] - javascript

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/

Related

move option from one select to another select with JS

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>

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;
}

JavaScript Multi Select Box not posting all items

I found a nice demo on an old JSFIddle for Moving items from one multi-select box to another with JavaScript
You can see the demo here: http://jsfiddle.net/jasondavis/e6Y7J/25/
The problem is, the visual part works correctly but when I put this on a server with PHP, it only POST the last item added to the new select box. So instead of POSTING an array of items, it will only POST 1 item regardless of how many items exist in the selection box.
Can anyone help me?
The JavaScript/jQuery
$(document).ready(function() {
$('select').change(function() {
var $this = $(this);
$this.siblings('select').append($this.find('option:selected')); // append selected option to sibling
});
});
I believe I've hit this issue before. For the PHP $_POST array to populate this correctly you need to add a name field with [] at the end of the name. PHP will then interpret the result as an array of all the values and not just the last selected one.
Example:
<select name="demo_multi[]" multiple="multiple">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
When you recall the item in the $_POST array leave off the square brackets.
$values = $_POST['demo_multi'];
Change the multiselect name to an array
<select name="post_status[]" multiple id="select2" class="whatever" style="height: 500px; width: 222px;"></select>
I think you also have to select all items in the
This is pre jquery but it works.
`<form onsubmit="selectAll();"> ....</form>
function selectAll()
{
for(j=0; j<document.formdata.elements.length; j++)
{
// if a multiple select box then select all items in the box so they are sent with the form
var currObj = document.formdata.elements[j];
if (currObj.tagName == 'SELECT' && currObj.multiple == true)
for (i=0; i<currObj.length; i++)
currObj.options[i].selected = true;
}
}`
This will then be loaded into the array named in the

Loop over Dropdownlist

I want to loop over a Dropdownlist and write the value of the selected Item in a label.
I've done it before with a selection of Radio buttons but with the dropdownlist it won't work.
Now, some Code.
Here is the generated HTML Code Values are not interesting.
<select id="alternativeNumbers" name="alternativeNumbers">
<option value="1_A">Text</option>
<option value="2_B">Text</option>
<option value="3_C">Text</option>
<option value="4_D">Text</option>
<option value="5_E">Text</option>
<option value="6_F">Text</option>
</select>
The Code to bind the event to the Dropdownlist.
$(function () {
var dropdown = document.getElementsByName("alternativeNumbers");
$(dropdown ).change(function () {
updateAlternativeDropdown();
});
});
And finally the method which is called by the event. This should fill the labels.
function updateAlternativeDropdown() {
var dropdown = document.getElementsByName("alternativeNumbers");
var lengthDropDown = addAlternativeArticleNumberDropdown.length;
for (var i=0; i < lengthDropDown; i++)
{
//This alert is for the behavior of the output!
alert(addAlternativeArticleNumberDropdown[i].value);
if (addAlternativeArticleNumberDropdown[i].selected) {
var valueOfDropdown = addAlternativeArticleNumberDropdown[i].value;
var splittedValues = valueOfDropdown.split("_");
document.getElementById("label1").innerText = splittedValues[0];
document.getElementById("label2").innerText = splittedValues[1];
}
}
};
I hope this is enough information, now the Problem / Current behavior:
The method updateAlternativeDropdown() is called fine but then the alert inside the loop returns the value of first element, value of the selected element and this 3 times. (I guess because of the 6 elements in this element)
Furthermore because of this my if-statement isn't entered. Currently I#m kind of clueless where this problem comes from.
Thanks in advance.
You don't have to iterate dropdown's options. You can access selected option like this:
dropdown.options[dropdown.selectedIndex].value
Update your updateAlternativeDropdown function:
function updateAlternativeDropdown() {
var dropdown = document.getElementById("alternativeNumbers"),
splittedValues = dropdown.options[dropdown.selectedIndex].value.split('_');
document.getElementById("label1").innerHTML = splittedValues[0];
document.getElementById("label2").innerHTML = splittedValues[1];
}
$('#alternativeNumbers').change(updateAlternativeDropdown);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
label1: <span id="label1">-</span><br />
label2: <span id="label2">-</span><br />
<select id="alternativeNumbers" name="alternativeNumbers">
<option value="1_A">Text</option>
<option value="2_B">Text</option>
<option value="3_C">Text</option>
<option value="4_D">Text</option>
<option value="5_E">Text</option>
<option value="6_F">Text</option>
</select>
working Example

2 related Multiselect form elements

I want to create 2 multiselect side by side. The first one is populated, but the 2nd is empty. The 2nd gets populated only when I select an option from the 1st one and depends on the value of the 1st one.
I'm thinking the only way to do this is with javascript. Can someone confirm this, and do you know of existing examples.
I'm using jquery, but prefer to not use plugins.
I'm also thinking to use Zend so if an existing component exists that would be great.
Here's a demo
You can easily do this with some DOM manipulation.
HTML
<select id="from" multiple>
<option value="-">King</option>
<option value="9">Queen</option>
<option value="5">Rook</option>
<option value="3">Knight</option>
<option value="3">Bishop</option>
<option value="1">pawn</option>
</select>
<select id="to" multiple>
</select>
javascript
var from = document.getElementById("from");
var to = document.getElementById("to");
from.onchange = function(){
//remove this to allow for duplicates
to.innerHTML = "";
var fromOptions = from.getElementsByTagName("option");
for(var i in fromOptions) {
if (fromOptions[i].selected == true) {
//remove "cloneNode(true)" to simultaniusly
//remove the node from the from list.
to.appendChild(fromOptions[i].cloneNode(true));
}
}
}

Categories