Javascript store <select> dropdown values within array - javascript

I'm wondering if it's possible to store the selected values from a <select>in a JS array.
What I finally need to do is calculate the highest 6 values out of around 10 dropdowns, which I think I can do by using the JS Math.max() function.
Help is greatly appreciated.
Here is some sample code:
<? while($subjects = mysql_fetch_array($query)) { ?>
<select class="points">
<optgroup label="<?=$subjects['name']?>">
<option value="100">A1</option>
<option value="90">A2</option>
<option value="85">B1</option>
<option value="80">B2</option>
<option value="75">B3</option>
</optgroup>
</select>
<? } ?>
<script>....

Do something like this (JQuery):
var selected = new Array();
$('.points option:selected').each(function() {
selected.push($(this).val());
});

var selects = [].slice.apply(document.getElementsByTagName('select'));
selects.forEach(function (elem, i){
var value = elem.options[elem.selectedIndex].value;
//Do something with this value. Push it to an array, perhaps.
});​
This assumes that all the selects on the page should be included. If that isn't the case, then you should use document.getElementsByClassName or a similar, more appropriate selector instead.
Demo

Try this:
var selectValues = [];
var selectNodeList = document.getElementsByClassName("points");
for (var i = 0; i < selectNodeList.length; i++) {
selectValues.push(selectNodeList[i].value)
}
// selectValues array now stores values of all <select> lists with class "points"

Related

There is a way to get all the option values in the SELECT TAG without an ID?

do you know if there is a way to take all the values in the OPTION VALUE included in a SELECT?
i Will show you an example, I have this code:
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1 >MIPS
<OPTION VALUE=MSU1 >MSU
<OPTION VALUE=PERCEN1 >% CEC
<OPTION VALUE=NUMGCP1 >nCPU
</SELECT>
I only know the first value which is MIPS1, and I need to take the other values. The is a way to write that if I know the first MIPS1 I will search for the other values Included from the ?
Thanks in advance :)
You can get the <select> element that has an option with a specific value using something like this:
const select = document.querySelector('option[value=MIPS1]').closest('select');
Once you have the <select> element you can retrieve it's options using something like this:
const options = select.querySelectorAll('option');
Or:
const options = select.options;
As #charlietfl mentioned, .closest is not supported by all browsers, instead of that, you could use .parentElement.
jQuery version
var opt = "MIPS1";
const $sel = $("option[value='"+opt+"']").parent()
const options = $("option",$sel).map(function() { return this.value }).get()
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1>MIPS
<OPTION VALUE=MSU1>MSU
<OPTION VALUE=PERCEN1>% CEC
<OPTION VALUE=NUMGCP1>nCPU
</SELECT>
The example below shows how you can do this. The Jquery is fully commented.
Let me know if it isn't what you were hoping for.
Demo
// Create array
var options = [];
// Load option value you're looking for into a variable
var search_term = "MIPS1";
// Find option with known value, travel up DOM tree to select and then find all options within it
$("option[value='" + search_term + "']").closest("select").find("option").each(function() {
// Add values to array
options.push($(this).val());
});
// Print the array
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1>MIPS
<OPTION VALUE=MSU1>MSU
<OPTION VALUE=PERCEN1>% CEC
<OPTION VALUE=NUMGCP1>nCPU
</SELECT>
I think it is a bad idea not to give id to your html element in the first place, however if you need to do it that way, then the code below assumes you have only one select tag on your page.
let select = document.querySelector('select');
options = select.childNodes.filter((c) => c.tagName==='OPTION')
.map((o) => o.value);
console.log(options)
This will help you get: selected value, selected text and all the values in the dropdown.
$(document).ready(function(){
$("button").click(function(){
var option = $('option[value="MIPS1"]');
var select = option.parent();
var value = $(select).find(":selected").val();
var optionName = $(select).find(":selected").text();
var result = "value = "+value+"\noption name = "+optionName+"\nall values = ";
$(select).each(function(){
result+=($(this).text()+" ");
});
console.log(result);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value=MIPS1 >MIPS</option>
<option value=MSU1 >MSU</option>
<option value=PERCEN1 >% CEC</option>
<option value=NUMGCP1 >nCPU</option>
</select>
<button>click</button>

getElementById selected can't select more than one option

I have a function in javascript that should allow me to select more than one option, but it only selects the first one.
Javascript:
function index(){
var a="${staffindex}".replace("[","");
var b=a.replace("]","");
var index1=b.split(",");
for(var i=0;i<index1.length;i++)
document.getElementById("Staff")[index1[i]].selected=true;
}
HTML:
<select multiple="multiple" id="Staff" name=staff>
<option value = "1" >option1</option>
<option value = "2" >option2</option>
<option value = "3" >option3</option>
<option value = "4" >option4</option>
<option value = "5" >option5</option>
</select>
index1 is an array of numbers received from a java class.
Thanks for any help!
You forget to use options array:
document.getElementById("Staff").options[index1[i]].selected=true;
getElementById() function in javascript selects only one element. Here it only selects the <select> tag since it has the id as Staff and not its options. You can however access its options as
getElementById("Staff").options[option_number];
Try this:
function index(){
var a="${staffindex}".replace("[","");
var b=a.replace("]","");
var index1=b.split(",");
for(var i=0;i<index1.length;i++)
document.getElementById("Staff").options[index1[i]].selected=true;
}
That options is very neccessary here!

JavaScript to select multiple select list values

I have the following select list from which the user can select multiple values.
<select name="valumethod1[]" id="valumethod1[]" onBlur="validatevalumethod()" size="6">
<option value ="t1">test1</option>
<option value ="t2">test2</option>
<option value ="t3">test3</option>
<option value ="t4">test4</option>
</select>
I want to fetch the selected values in JavaScript, but I don't know how to do this. Please help me.
Try something like this :
var ob = document.getElementById('valumethod1[]');
var selected = new Array();
for (var i = 0; i < ob.options.length; i++) {
if (ob.options[ i ].selected) {
selected.push(ob.options[ i ].value);
}
}
The array selected is then an array of selected options. Working example here
Note: you need to add multiple="multiple" to your select list as an attribute

How can I replace all option labels of a select with their values?

If I have select element with values which are different from their labels, how can I replace all of the labels with the corresponding values?
Secondly, how can I sort the list alphabetically with the values, all without using any frameworks?
Input:
<select name="options" >
<option value="apple">Fruit</option>
<option value="rye">Bread</option>
<option value="beer">Beverage</option>
</select>
Output:
<select name="options" >
<option value="apple">apple</option>
<option value="beer">beer</option>
<option value="rye">rye</option>
</select>
Sure, using getElementsByTagName() and innerHTML:
var allOptions = document.getElementsByTagName("option");
for (var i=0; i<allOptions.length; i++) {
allOptions[i].innerHTML = allOptions[i].value;
}
Here it is in action.
To sort the options alphabetically, see: Javascript to sort contents of select element
If you would like them to be identical, you can simply omit the value attribute - the string inside the option tag will then be sent to the server as the value. Take a look here: http://www.w3schools.com/tags/att_option_value.asp.
You can do this:
<select name="options" >
<option value="apple">Fruit</option>
<option value="rye">Bread</option>
<option value="beer">Beverage</option>
</select>
<script>
var options = document.getElementsByName("options")[0].querySelectorAll("option");
Array.prototype.slice.call(options).map(function (option) {
option.innerHTML = option.value;
});
</script>
You can encapsulate this in a function to order your select, and order when you remove or add any element to your select.
The function would be something like this:
function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
And you should call it like :
sortSelect(document.getElementsByName("options"));

How to get all options of a select using jQuery?

How can I get all the options of a select through jQuery by passing on its ID?
I am only looking to get their values, not the text.
Use:
$("#id option").each(function()
{
// Add $(this).val() to your list
});
.each() | jQuery API Documentation
Without jQuery
I do know that the HTMLSelectElement element contains an options property, which is a HTMLOptionsCollection.
const myOpts = document.getElementById('yourselect').options;
console.log(myOpts[0].value) //=> Value of the first option
A 12 year old answer. Let's modernize it a bit (using .querySelectorAll, spreading the resulting HTMLOptionsCollection to Array and map the values).
// helper to retrieve an array of elements using a css selector
const nodes = selector => [...document.querySelectorAll(selector)];
const results = {
pojs: nodes(`#demo option`).map(o => o.value),
jq: $(`#demo option`).toArray().map( o => o.value ),
}
console.log( `pojs: [${results.pojs.slice(0, 5)}]` );
console.log( `jq: [${results.jq.slice(0, 5)}]` );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="demo">
<option value="Belgium">Belgium</option>
<option value="Botswana">Botswana</option>
<option value="Burkina Faso">Burkina Faso</option>
<option value="Burundi">Burundi</option>
<option value="China">China</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="Malaysia">Malaysia</option>
<option value="Mali">Mali</option>
<option value="Namibia">Namibia</option>
<option value="Netherlands">Netherlands</option>
<option value="North Korea">North Korea</option>
<option value="South Korea">South Korea</option>
<option value="Spain">Spain</option>
<option value="Sweden">Sweden</option>
<option value="Uzbekistan">Uzbekistan</option>
<option value="Zimbabwe">Zimbabwe</option>
</select>
$.map is probably the most efficient way to do this.
var options = $('#selectBox option');
var values = $.map(options ,function(option) {
return option.value;
});
You can add change options to $('#selectBox option:selected') if you only want the ones that are selected.
The first line selects all of the checkboxes and puts their jQuery element into a variable. We then use the .map function of jQuery to apply a function to each of the elements of that variable; all we are doing is returning the value of each element as that is all we care about. Because we are returning them inside of the map function it actually builds an array of the values just as requested.
Some answers uses each, but map is a better alternative here IMHO:
$("select#example option").map(function() {return $(this).val();}).get();
There are (at least) two map functions in jQuery. Thomas Petersen's answer uses "Utilities/jQuery.map"; this answer uses "Traversing/map" (and therefore a little cleaner code).
It depends on what you are going to do with the values. If you, let's say, want to return the values from a function, map is probably the better alternative. But if you are going to use the values directly you probably want each.
$('select#id').find('option').each(function() {
alert($(this).val());
});
This will put the option values of #myselectbox into a nice clean array for you:
// First, get the elements into a list
var options = $('#myselectbox option');
// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())
$("#id option").each(function()
{
$(this).prop('selected', true);
});
Although, the CORRECT way is to set the DOM property of the element, like so:
$("#id option").each(function(){
$(this).attr('selected', true);
});
You can take all your "selected values" by the name of the checkboxes and present them in a sting separated by ",".
A nice way to do this is to use jQuery's $.map():
var selected_val = $.map($("input[name='d_name']:checked"), function(a)
{
return a.value;
}).join(',');
alert(selected_val);
Working example
The most efficient way to do this is to use $.map()
Example:
var values = $.map($('#selectBox option'), function(ele) {
return ele.value;
});
You can use following code for that:
var assignedRoleId = new Array();
$('#RolesListAssigned option').each(function(){
assignedRoleId.push(this.value);
});
For multiselect option:
$('#test').val() returns list of selected values.
$('#test option').length returns total number of options (both selected and not selected)
Another way would be to use toArray() in order to use fat arrow function with map e.g:
const options = $('#myselect option').toArray().map(it => $(it).val())
Here is a simple example in jquery to get all the values, texts, or value of the selected item, or text of the selected item
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
printOptionValues = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
}
printOptionTexts = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).text());
})
}
printSelectedItemText = () => {
console.log($('#nCS1 option:selected').text());
}
printSelectedItemValue = () => {
console.log($('#nCS1 option:selected').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="1" id="nCS1" name="nCS1" class="form-control" >
<option value="22">Australia</option>
<option value="23">Brunei</option>
<option value="33">Cambodia</option>
<option value="32">Canada</option>
<option value="27">Dubai</option>
<option value="28">Indonesia</option>
<option value="25">Malaysia</option>
</select>
<br/>
<input type='button' onclick='printOptionValues()' value='print option values' />
<br/>
<input type='button' onclick='printOptionTexts()' value='print option texts' />
<br/>
<input type='button' onclick='printSelectedItemText()' value='print selected option text'/>
<br/>
<input type='button' onclick='printSelectedItemValue()' value='print selected option value' />
var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +' value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
});
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);
This is a simple Script with jQuery:
var items = $("#IDSELECT > option").map(function() {
var opt = {};
opt[$(this).val()] = $(this).text();
return opt;
}).get();
var selectvalues = [];
for(var i = 0; i < items.length; i++) {
for(key in items[i]) {
var id = key;
var text = items[i][key];
item = {}
item ["id"] = id;
item ["text"] = text;
selectvalues.push(item);
}
}
console.log(selectvalues);
copy(selectvalues);
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
This is a very simple way to generate a list of comma separated values.
var values = "";
$('#sel-box option').each(function () {
values = values + $(this).val() + ";";
});
$("input[type=checkbox][checked]").serializeArray();
Or:
$(".some_class[type=checkbox][checked]").serializeArray();
To see the results:
alert($("input[type=checkbox][checked]").serializeArray().toSource());
If you're looking for all options with some selected text then the below code will work.
$('#test').find("select option:contains('B')").filter(":selected");
The short way
$(() => {
$('#myselect option').each((index, data) => {
console.log(data.attributes.value.value)
})})
or
export function GetSelectValues(id) {
const mData = document.getElementById(id);
let arry = [];
for (let index = 0; index < mData.children.length; index++) {
arry.push(mData.children[index].value);
}
return arry;}
I found it short and simple, and can be tested in Dev Tool console itself.
$('#id option').each( (index,element)=>console.log( index : ${index}, value : ${element.value}, text : ${element.text}) )
$("select#MY_SELECT_ID").find('option').each(function() {
console.log($(this).val());
console.log($(this).text());
});

Categories