Every relevant "question that may already have [my] answer" uses jQuery, which I am not using.
So, is there any simple way to get the values of selected options in a <select multiple> tag, or do I have to loop through all the options to see which ones are selected and manually build an array?
Side-question: Which browsers don't support selectElement.value and instead require selectElement.options[selectElement.selectedIndex].value?
You can use select.selectedOptions. However, this returns an HTMLCollection, so you still have to clean it to get a string array. http://jsfiddle.net/9gd9v/
<select multiple>
<option value="foo" selected>foo</option>
<option value="bar">bar</option>
<option value="baz" selected>baz</option>
</select>
and:
var select = document.querySelector("select");
var values = [].map.call(select.selectedOptions, function(option) {
return option.value;
});
If you end up wanting to loop through and grab the selected values you could use something like this:
function loopSelected()
{
var txtSelectedValuesObj = "";
var selectedArray = new Array();
var selObj = document.getElementById('selectID');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj = selectedArray;
alert(txtSelectedValuesObj);
}
You can view an example HERE, adapted from this example.
.
You could also simply track the selected options via the onchange event in real-time and collect them whenever you want them. I admit it's still looping, but at least you're not doing it every time you need to retrieve the selected options, and it has the added bonus of being simple (come retrieval time, anyway...). Working fiddle: http://jsfiddle.net/cyg9Z/
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trackSelected = function (e) {
var selector = document.getElementById('selector'),
selected = [],
i = 0;
for (i = 0; i < selector.children.length; i += 1) {
if (selector.children[i].selected) {
selected.push(selector.children[i].value)
}
}
selector.selMap = selected;
};
Test.addListeners = function () {
var selector = document.getElementById('selector'),
tester = document.getElementById('tester');
selector.onchange = Test.trackSelected;
tester.onclick = Test.testSelected;
};
Test.testSelected = function () {
var div = document.createElement('div');
div.innerText = document.getElementById('selector').selMap.join(', ');
document.body.appendChild(div);
};
Test.addListeners();
}());
Related
Image of empty list
Showing populated options within inspector
I dynamically add options through a JS file based on the DB items. They sometimes populate when I CTRL+SHIFT+R hard refresh the page but not every time.
They never populate when I do a regular refresh (ctrl+r).
I am genuinely so confused how the options could be populated inside the inspector but not actually visible..
The JS is also surrounded with $(document).ready(function ()) so to my knowledge it only runs once the page is ready.
Function where I populate one of the dropdowns
function renderEndUseDropdown()
{
var endUseList = new Set(filteredProductList.map((element) => element.endUse));
var endUse = Array.from(endUseList);
var endUseSelection = document.getElementById("processname");
for(var i = 0; i < endUse.length; i++)
{
if(endUse[i] !== '')
{
var option = endUse[i];
var displayElement = document.createElement("option");
displayElement.textContent = option;
displayElement.value = option;
endUseSelection.add(displayElement);
}
}
}
The above code would be adding options to this block of HTML
<div class="col-xs-12 col-sm-6 col-md-2">
<select class="selectpicker" multiple="multiple" data-live-search="true" title="End Use" id="processname" multiple data-actions-box="true">
</select>
</div>
Since you are using bootstrap-select, this needs to be done.
So your function could be updated like below.
function renderEndUseDropdown()
{
var endUseList = new Set(filteredProductList.map((element) => element.endUse));
var endUse = Array.from(endUseList);
var endUseSelection = document.getElementById("processname");
for(var i = 0; i < endUse.length; i++)
{
if(endUse[i] !== '')
{
var option = endUse[i];
var displayElement = document.createElement("option");
displayElement.textContent = option;
displayElement.value = option;
endUseSelection.add(displayElement);
}
}
$('#processname').selectpicker('refresh');
}
I have a constructor and have created some instances of it which I have placed in an array. What I am trying to do is to display the value of said object into the empty list depending on what I choose from a list of options. Here is what I have done so far:
<ul id="contactinfo"></ul>
<select id="dropdown">
<option value="email">Email</option>
<option value="number">Phone Number</option>
</select>
function ContactList (name, email, number) {
this.name = name;
this.email = email;
this.number = number;
}
var christian = new ContactList('Christian', 'christian#yahoo.com', '323-555-124');
var contactarray = [christian];
function displayinfo () {
var dropdown = $('#dropdown').val();
var number = $('#dropdown').val('number');
var email = $('#dropdown').val('email');
for (i = 0; i < contactarray.length; i++) {
if (dropdown == number) {
$('#contactinfo').append('<li>' + contactarray[i].number + '</li>');
} else {
$('#contactinfo').append('<li>' + contactarray[i].email + '</li>');
}
}
}
displayinfo();
Firstly, note that the main issue with your current code is that $('#dropdown').val(), $('#dropdown').val('number') and $('#dropdown').val('email') all return the same thing - the dropdown in a jQuery object. Also note the latter two are also setting the value to that provided, so the JS would always only retrieve the email as that was what is set last.
To fix it, you can take the value selected in the dropdown and retrieve that property from the contactarray element directly. Try this:
function displayinfo () {
var $contacts = $('#contactinfo').empty();
for (i = 0; i < contactarray.length; i++) {
$contacts.append('<li>' + contactarray[i][$('#dropdown').val()] + '</li>');
}
}
Finally, you also need to execute displayinfo when the option in the select is changed, and also clear out any previously appended li. Check out the fiddle below for a full working example:
Working example
I have created a javascript search in select element.
option tag does not get any CSS to hide or display none, for this solution I have removed unmatched option and make a backup for removed option for reset list button.
It's working fine but I have a problem, I have about 19000 option for this select list.
search works fine but when I hit reset button, only 9500 option from 19000 comes back.
I appreciate your help.
Here is the code:
CodePen Demo
HTML
<h1>Search in select "option" tag</h1>
<select multiple name="selectMenu" id="selectMenu" style="width:100px" size=10>
<option value ="item 1">item 1</option>
<option value ="item 2">item 2</option>
<option value ="thing 3">thing 3</option>
<option value ="item 4">item 4</option>
<option value ="stuff 5">stuff 5</option>
<option value ="stuff 6">stuff 6</option>
<option value ="stuff 7">stuff 7</option>
<option value ="item 8">item 8</option>
</select>
<p>Search within this list</p>
<input type=text name="search" id="search" onkeypress="searchItems();">
<br>
<input type=button value="Search" onclick="searchItems();">
<input type=button value="Reset List" onclick="resetList();">
Javascript
var itemList = null;
var itemListOriginal = new Array();
var backup = false;
function searchItems() {
itemList = document.getElementById("selectMenu");
var searchStrObj = document.getElementById("search");
var itemDescription = "";
// replace white space with wild card
var searchString = searchStrObj.value;
searchString = searchString.replace(" ", ".*");
var re = new RegExp("(" + searchString + ")", "i"); //"i" sets "ignore case" flag
if (itemListOriginal.length < 1)
backup = true;
else
backup = false;
// loop through options and check for matches
for (i=itemList.options.length - 1; i >=0 ; i--) {
itemDescription = itemList.options.item(i).text;
if (backup) {
hash = new Array();
hash['name'] = itemDescription;
hash['value'] = itemList.options.item(i).value;
itemListOriginal[i] = hash;
}
if (!itemDescription.match(re)) {
itemList.remove(i);
}
}
return false;
}
function resetList() {
//hack! remove all elements from list before repopulating
for (i=itemList.options.length - 1; i >=0 ; i--) {
itemList.remove(i);
}
for (i=0; i < itemListOriginal.length; i++) {
hash = itemListOriginal[i];
//option = new Option(hash['name'], hash['value']); REMOVED
//itemList.options.add(option, i); REMOVED
itemList.options[i] = new Option(hash['name'], hash['value'], false, false);
}
document.getElementById("search").value = "";
}
DEMO
I've observed that in your code backup is changed every time you call the function searchitems().
Thus erasing the old values that were stored in it.
So I've changed that
It is working fine but I have a problem,
I have about 19000 option for this select list.
search works fine but when I hit reset button,
only 9500 option from 19000 comes back.
That is the reason behind that. So I've modified your code and added a global variable backupList in that.
so when the unwanted elements are removed old elements aren't deleted in my code but instead, new removed elements are appended to old removed elements using += shorthand operator.
also rather creating options dynamically and using .add or .append or any similar javascript method I'm using .innerHTML for simplicity as you can see in the code. only problem is that now after you click reset elements will not be sorted as it was in the first case, You'll need to sort them believe me it is easy. for sorting refer: sort select menu alphabetically?.
var itemList = null;
var itemListOriginal = new Array();
var backup = false;
var backupList =""; // To store removed elements
function searchItems() {
itemList = document.getElementById("selectMenu");
var searchStrObj = document.getElementById("search");
var itemDescription = "";
var searchString = searchStrObj.value;
searchString = searchString.replace(" ", ".*");
var re = new RegExp("(" + searchString + ")", "i"); //"i" sets "ignore case" flag
for (i=itemList.options.length - 1; i >=0 ; i--) {
itemDescription = itemList.options.item(i).text;
var hash = new Array();
hash['name'] = itemDescription;
hash['value'] = itemList.options.item(i).value;
itemListOriginal[i] = hash;
if (!itemDescription.match(re)) {
itemList.remove(i); //Remove Unwanted Elements
backupList+="<option value='"+ hash['value']+"'>"+itemDescription+"</option>";
/* append new unwanted elements with previous,
initially it is blank "".
This is Important
*/
}
}
return false;
}
function resetList() {
var itemList = document.getElementById("selectMenu");
itemList.innerHTML+=backupList; /* Add removed elements to list.
alternate to .append,.add or similar function*/
backupList=""; // Make Backup Empty!
document.getElementById("search").value = "";
}
Hope it helps! cheers :)!
I have a multiple select box and I want to access the selected data in javascript.
Here is the code:
<form onsubmit="return false;" id="multisel">
<select name="a[]" id="a" multiple style="width:350px;" tabindex="4">
<option value="Pedro">1</option>
<option value="Alexis">2</option>
<option value="Messi">3</option>
<option value="Villa">4</option>
<option value="Andres">5</option>
<option value="Sergio">6</option>
<option value="Xavi">7</option>
</select>
<button id="btn1" onclick="ajaxmultiselect()" type="submit" class="btn btn-primary">Save changes</button>
<p id="status"></p>
</form>
Here is the code I have tried so far :
<script>
function ajaxmultiselect(){
var input = [];
input = document.getElementById("a").value;
var status = _("status");
if(input == ""){
status.innerHTML = "Fill out all of the form data";
}else {
status.innerHTML = input;
}
}
</script>
When I run the code it only gives the first value.
I tried to access the values in php and it works fine, it passes the value as an array in php. Why isn't it doing the same with javascript?
I also tried to run a loop for the length of the value but that calculates the length of the first selection only.
I want to display all the values that will be selected.
Any help will be appreciated.
You can do the following:
function getSelectedOptions(element) {
// validate element
if(!element || !element.options)
return []; //or null?
// return HTML5 implementation of selectedOptions instead.
if (element.selectedOptions)
return element.selectedOptions;
// you are here because your browser doesn't have the HTML5 selectedOptions
var opts = element.options;
var selectedOptions = [];
for(var i = 0; i < opts.length; i++) {
if(opts[i].selected) {
selectedOptions.push(opts[i]);
}
}
return selectedOptions;
}
and then change your ajaxmultiselect() so you call it like this:
input = getSelectedOptions(document.getElementById("a"));
You will have to iterate for the values tho.
If you are wanting to get multiple selected items you could try something like the following:
function GetSelectedItems() {
var select = document.forms[0].a;
var selectedList = [];
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].selected) {
selectedList.push(select.options[i].value);
}
}
alert(Array.join(selectedList, ","));
}
For a given <select> element, all of the selected options are in the selectedOptions property. The selectedIndex property has the index of the first selected option, or -1 if there is no selection. Each of the options are the DOM object for that element, so their value is in the value property. So:
function ajaxmultiselect(){
var input = [];
var select = document.forms[0].a;
var status = _("status");
var options = select.selectedOptions;
if(select.selectedIndex == -1){
// no selection
status.innerHTML = "Fill out all of the form data";
}else {
for (var i = 0; i < options.length)
input.push(options[i].value);
status.innerHTML = input.join(", ");
}
}
From there you should be able to derive whatever you want.
document.getElementById('a').options //All Options
This will give you an array of options that you can iterate through.
I'm using a multiselect combobox, i select few values from the combobox and save the selected values to db. when i reopen the page, i need the focus to be placed on the values which was selected and saved.
function getSelectedValues() {
var from = document.getElementById("309127");
var to;
var v = from.options.length;
var selectedValues = "";
for (var i = 0; i < v; i++) {
if (from.options[i] && from.options[i].selected) {
var CVal = from.options[i].value;
var CText = from.options[i].text;
if (selectedValues == "") {
selectedValues = CVal;
}
else {
selectedValues = selectedValues + "~" + CVal;
}
}
}
return selectedValues;
}
this is the javascript function i used to save the selected values in db.
can anybody help me out on how to get the focus back on selected items ?
thank you
To set the focus with javascript you can use
document.getElementById("309127").focus();
For your question I'm assuming you send the values to a PHP page or something similar to update the database. If so your problem will be getting the selected values when you return to your page. Two suggestions:
Use ajax to update the database so you dont need to exit the page,
Pass the selected values back to your page through GET or similar and set the focus on page load.
EDIT: -------------
For example if you pass the values through GET like (www.example.com?param1=three)
You can use javascript to select that value on load:
<html>
<body onload="load()">
<select id="example">
<option value="one"> one </option>
<option value="two"> two </option>
<option value="three"> three </option>
</select>
</body>
<script>
function load(){
var param1 = getParameterByName("param1");
var selected = document.getElementById('example');
var opts = selected.options.length;
for (var i=0; i<opts; i++){
if (selected.options[i].value == param1){
selected.options[i].selected = true;
break;
}
}
}
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
</script>
</html>
try var from = document.getElementById("309127");from.focus();