Pass Multiple Select Values to a Javascript API function - javascript

I will keep this simple. First, these are snippets extracted from a larger document. So yes, I have the proper headers and source references, etc.
I have a select box. I know how to call the function based on a single value selection. I want to know how specifically to call this function showOnly() when the select box allows for multiple values.
The select box is
<select id="select_a" name="color" multiple>
<option selected="selected" class="options">Select desired detail</option>
<option value="None" class="options" >None</option>
<option value="Investment Category" class="options">Investment Category</option>
<option value="Company" class="options">Company</option>
<option value="Budget Line" class="options">Budget Line</option>
<option value="Market" class="options">Market</option>
<option value="Organization" class="options">Organization</option>
<option value="Segment" class="options">Segment</option>
</select>
So, how do I connect multiple values to the function showOnly() below. With one value, showOnly() might look like this showOnly('Segment','Cars'). I know showOnly with multiple values would like showOnly('Segment,['Cars','Boats','Planes']). Here is the function showOnly()
function showOnly(filterName, values) {
sheet = mainViz.getWorkbook().getActiveSheet();
if(sheet.getSheetType() === 'worksheet') {
sheet.applyFilterAsync(filterName, values, 'REPLACE');
} else {
worksheetArray = sheet.getWorksheets();
for(var i = 0; i < worksheetArray.length; i++) {
worksheetArray[i].applyFilterAsync(filterName, values, 'REPLACE');
}
}
};
Thoughts?? //Thanks for your consideration.

var colOfSelectedOpt = document.getElementById("select_a").selectedOptions;
var values = [];
for(var i=0;i<colOfSelectedOpt.length;i++) {
values.push(colOfSelectedOpt[i].value);
}
values should give you array of selected items. You can pass this to function before calling or pass the id of select and get values inside function.
Update
function showOnly(filterName, idOfSelect) {
var colOfSelectedOpt = document.getElementById(idOfSelect).selectedOptions;
var values = [];
for(var i=0;i<colOfSelectedOpt.length;i++) {
values.push(colOfSelectedOpt[i].value);
}
sheet = mainViz.getWorkbook().getActiveSheet();
if(sheet.getSheetType() === 'worksheet') {
sheet.applyFilterAsync(filterName, values, 'REPLACE');
} else {
worksheetArray = sheet.getWorksheets();
for(var i = 0; i < worksheetArray.length; i++) {
worksheetArray[i].applyFilterAsync(filterName, values, 'REPLACE');
}
}
};
Whenever you call showOnly() method pass the id of select dom for which you want this function to get called.
<select id="select_a" name="color" onchange="showOnly('filterName', this.getAttribute('id'));" multiple>
Or If you want selection to work on some other button then fetch and id from associated select dropdown by id and pass it to function.

There's an object built-in Function as a property called arguments which is a local variable that can pass in an unlimited amount of values. arguments is array-like in that it will index every value it's given and it has a couple of methods including length. I have no idea if my example works since half of those functions and variables are not provided. collArgs() should be able to take a number of parameters and return the values in an indexed array-like fashion. From there, I've assigned values to store the values of arguments and now it can be passed into your functions.
Please read this article for a better explanation and working examples
args = new arguments()
function collArgs() {
for (var i = 0; i < arguments.length; i++) {
arguments[i];
}
return arguments;
}
var values = collArgs();
function showOnly(filterName, values) {
var sheet = mainViz.getWorkbook().getActiveSheet();
if(sheet.getSheetType() === 'worksheet') {
sheet.applyFilterAsync(filterName, values, 'REPLACE');
} else {
var worksheetArray = sheet.getWorksheets();
for(var i = 0; i < worksheetArray.length; i++) {
worksheetArray[i].applyFilterAsync(filterName, values, 'REPLACE');
}
}
};

Since HTMLOptionsCollection's are array-like objects, I'm not familiar with any way to use Array.prototype.map() to create a new array of selected values. But we can alway use the good old fashioned for loop. Here's an ES6 approach:
const select = document.getElementById('select_a');
const on_change = (event) => {
const options = event.target.options;
let values = [];
for (var i = 0; i < options.length; i++) {
if (options[i].selected) {
values.push(options[i].value);
}
}
console.log('Pass these values to your function:', values);
};
select.addEventListener('change', on_change);
JS Bin: http://jsbin.com/yemoxizaso/1/edit?js,console,output
And if you can't use ES6, here's an ES5 approach:
var select = document.getElementById('select_a');
var on_change = function(event) {
var options = event.target.options;
var values = [];
for (var i = 0; i < options.length; i++) {
if (options[i].selected) {
values.push(options[i].value);
}
}
console.log('Pass these values to your function:', values);
};
select.addEventListener('change', on_change);

Related

underscore js _grouby Browser Difference

I'm seeing some strange behavior with the order in which a select's optgroups and options are being rendered. I have some data that is used to build optgroup in a select and then options using the underscore js _grouby function. Firefox is rendering the data the way I ordered the json, Chrome and IE are displaying it in reverse order.
Here's a Fiddle
Html:
<select name="dropdownlist" id="dropdownlist">
<option value="All">All</option>
</select>
JavaScript:
$(document).ready(function() {
var dataresults = [{"MonthName":"April","Month":4,"Year":2014,"Date":"\/Date(1397451600000)\/"},{"MonthName":"January","Month":1,"Year":2014,"Date":"\/Date(1388556000000)\/"},{"MonthName":"November","Month":11,"Year":2013,"Date":"\/Date(1384322400000)\/"},{"MonthName":"July","Month":7,"Year":2013,"Date":"\/Date(1373864400000)\/"}];
BindYearDropDown(dataresults);
function BindYearDropDown(data)
{
var groupData = _.groupBy(data, function (obj) {
return obj.Year;
});
var optGroups = [];
for (var key in groupData) {
if (groupData.hasOwnProperty(key)) {
var optGroup = $("<optgroup></optgroup>");
optGroup.attr("label", key);
optGroup.attr("id", key);
var currentGroup = groupData[key];
for (var i = 0; i < currentGroup.length; i++) {
$("<option />").attr("value", currentGroup[i].Month).html(currentGroup[i].MonthName).appendTo(optGroup);
}
optGroups.push(optGroup);
}
}
//optGroups.reverse();
for (var i = 0; i < optGroups.length; i++) {
$('#dropdownlist').append(optGroups[i]);
}
};
FireFox Results: (This is how I would like the data displayed)
Chrome Results:
IE11 Results:
Thanks in advance,
KC
If you really want to work with the data in the structure you provided, you can create a list of years and then sort that. Otherwise, I recommend what #mu is too short suggested. jsfiddle
/* reusable descending sort function */
function sortDescending(value) {
return value * -1;
};
...
var groupData = _.groupBy(data, function (obj) {
return obj.Year;
});
/* Sort the years in descending order */
var years = _.sortBy(_.keys(groupData), sortDescending);
var optGroups = [];
for (var index in years) {
var key = years[index];
...

Getting Selected options from Multi Select tag via Javascript and Send via XHR

I'm looking to submit a form via an XHR but I'm having trouble getting a hold of the selected data to pass along.
<form>
<select multiple id="select" >
<option class="userOptions" value="1">Tyler Durden</option>
<option class="userOptions" value="2">Robert Paulson</option>
<option class="userOptions" value="3">Marla Singer</option>
</select>
</form>
What would be the best way to grab hold of the user selected values and pass them off to a page via an XHR?
I've tried things like document.getElementsByClassName("userOptions").selected but it's not returning anything. Also, should I pack this up as an array? Or is there a better way to send it? Thanks for your time!
Here is a function in vanilla Javascript that will help you:
function getMultiValue(selectId)
{
var list = document.getElementById(selectId),
selected = [],
i;
for (i = 0; i < list.options.length; i++) {
if (list.options[i].selected) {
selected.push(list.options[i].value);
}
}
return selected;
}
In the case of your example, you must use this way:
var values = getMultiValue('select');
If you want those values converted to a query string:
var queryString = 'select=' + values.implode('&select=');
If the values contain special characters, you must do this before the construction of the query string:
var i;
for (i = 0; i < values.length; i++) {
values[i] = escape(values[i]);
}
Or just change a little the previous function:
function getMultiValue(selectId, mustEscape)
{
var list = document.getElementById(selectId),
selected = [],
i;
for (i = 0; i < list.options.length; i++) {
if (list.options[i].selected) {
selected.push(mustEscape ? escape(list.options[i].value) : list.options[i].value);
}
}
return selected;
}
And use it this way:
var values = getMultiValue('select', true),
queryString = 'select=' + values.implode('&select=');
Use jQuery and its just simple!
You can do it like this: http://jsfiddle.net/Hm2KL/
$("#sendbtn").click(function() {
var data = $("#selectme").val();
alert(data);
$.ajax({
url: ..,
data: {data}
etc..
});
});
jQuery Ajax Doc: http://api.jquery.com/jQuery.ajax/

How to set the selected index of a dropdown using javascript

How can I set the selected value of a dropdown using javascript?
This is my HTML:
<select id="strPlan" name="strPlan" class="formInput">
<option value="0">Select a Plan</option>
</select>
I am using javascript to add values. Can anyone tell me how to call a function to select a value?
How can I set the selected value of a dropdown using javascript?
So, you want to change the value of the option that is currently selected. Is that correct?
function setValueOfSelected(select, valueToSetTo){
select.options[select.selectedIndex].value = valueToSetTo;
}
And call it like this:
setValueOfSelected(document.getElementById('strPlan'), 'selected');
Demo
In case you meant that you want to select an option based on its value, use this:
Declare this function:
function setOptionByValue(select, value){
var options = select.options;
for(var i = 0, len = options.length; i < len; i++){
if(options[i].value === value){
select.selectedIndex = i;
return true; //Return so it breaks the loop and also lets you know if the function found an option by that value
}
}
return false; //Just to let you know it didn't find any option with that value.
}
Now call that to set the option by value, like this, with the first parameter being the select element and the second being the value:
setOptionByValue(document.getElementById('strPlan'), '1');
Demo
Something like this could work, I believe:
function setDropDownList(elementRef, valueToSetTo)
{
var isFound = false;
for (var i = 0; i < elementRef.options.length; i++) {
if (elementRef.options[i].value == valueToSetTo) {
elementRef.options[i].selected = true;
isFound = true;
}
}
if ( isFound == false )
elementRef.options[0].selected = true;
}
Found it here. Just Google for something like 'set selected value dropdown javascript' and you'll get many possible solutions.

How to get the index of an option in a select menu by matching the text with plain Javascript?

I have a select menu and I need to dynamically select the option based on the text value of the option element. For example, my select looks like this:
<select id="names">
<option value="">Please Select</option>
<option value="1">John</option>
<option value="2">Steve</option>
<option value="3">Max</option>
</select>
If I have the string "Max", how can I get that the index of the option is 4 so I can dynamically set this as the selectedIndex with JavaScript?
No jQuery.
http://jsfiddle.net/x8f7g/1/
You want to select the element, iterate over the array, find the text value, and return the index.
Don't use InnerHTML, it's slow and breaks and not standards compliant
Dont use innerText, simmilar reasons but not quite as serious
Do use a function so you can do it all over again.
Do select the child text node, and retreives the nodeValue, which is cross-browser friendly
Example:
function indexMatchingText(ele, text) {
for (var i=0; i<ele.length;i++) {
if (ele[i].childNodes[0].nodeValue === text){
return i;
}
}
return undefined;
}
Try this, it should find and then select the relevant option in the select box.
var searchtext = "max";
for (var i = 0; i < listbox.options.length; ++i) {
if (listbox.options[i].text === searchtext) listbox.options[i].selected = true;
}
var opts = document.getElementById("names").options;
for(var i = 0; i < opts.length; i++) {
if(opts[i].innerText == "Max") {
alert("found it at index " + i + " or number " + (i + 1));
break;
}
}
Demo.
in PLAIN js
var sel, opts, opt, x, txt;
txt='Max';
sel=document.getElementById('names');
opts=sel.options;
for (x=0;x<opts.lenght;x++){
if (opts[x].text === txt){
opt=opts[x];
}
}
The options property stores the options in a select menu - iterate over it and compare the contents.
var list = document.getElementById("names").options;
for(var i = 0; i<list.length; i++){
if(list[i].text== "Max") { //Compare
list[i].selected = true; //Select the option.
}
}
JSFiddle: http://jsfiddle.net/cuTxu/2
You could use this short function to do that:
function findIndexfromOptionName( select, optionName ) {
let options = Array.from( select.options );
return options.findIndex( (opt) => opt.label == optionName );
}
Arguments:
select: an HTMLSelect element
optionName: as a string
Explanation:
On the first line of the function body we retrieve the <select> options as an array using Array.from().
This allow us to use Array.prototype.findIndex() to return the index of the first option that match the provided name, if any or return -1 if there is no match.
Want some reasons to use it ?
It has a short implementation and the semantic is pretty clear. Also pure JS.
This should do the trick:
var options = document.getElementsByTagName('select')[0].children,
i,
l = options.length,
index;
for(i = 0; i < l; i++){
if(options[i].firstChild.nodeValue === 'Max'){index = i};
}
Please note that the index is zero based, what mean it is one less than you would expect.
var x = document.getElementById("names");
for(var i = 0; i<x.options.length; i++){
if("Max" == x.options[i].text){
doSomething();
//maybe x.selectedIndex = i;
}
}
[edit - expanded to include non-jquery method]
I strongly recommend using jQuery for this since the solution is a one-liner:
jQuery('#names option:contains("Max")').val()
However, here's a pure JavaScript implementation anyway:
function findOption( select, matchMe ) {
var
// list of child options
options = select.getElementsByTagName('option'),
// iteration vars
i = options.length,
text,
option;
while (i--) {
option = options[i];
text = option.textContent || option.innerText || '';
// (optional) add additional processing to text, such as trimming whitespace
text = text.replace(/^\s+|\s+$/g);
if (text === matchMe) {
return option.getAttribute('value');
}
}
return null;
}
Example usage:
alert(
findOption(
document.getElementsByTagName('select')[0],
"Max"
)
);
Alerts 3

JavaScript: get value of dropdown

I have 3 HTML combo/drop down boxes. All of them have a distinct name and id.
On a particular event I want to get the value of all three of them.
Can any one give me a code snippet for that?
using jQuery:
$("#dropdownID").val();
I'd try to set them up next to each other in your HTML and then iterate through them using jQuery's built-in each() method. You'd set up your elements like this:
<div id="dropdownBoxes">
<select id="firstElement">
<option>cool</option>
<option>neat</option>
</select>
<select id="secondElement">
<option>fun</option>
<option>awesome</option>
</select>
<select id="thirdElement">
<option>great</option>
<option>synonym</option>
</select>
</div>
<input type="button" id="theTrigger">Push me!</input>
Then, in your script:
var dropdownValues;
$("#theTrigger").click(function(){
dropdownValues.length=0;
$("#dropdownBoxes select").each(function(){
dropdownValues.push($(this).val());
});
});
To do this not using jQuery:
function getSelectValues() {
var values = [];
for (var i = 0; i < arguments.length; i++) {
var select = document.getElementById(arguments[i]);
if (select) {
values[i] = select.options[select.selectedIndex].value;
} else {
values[i] = null;
}
}
return values;
}
This function returns an array of values that correspond to the ids you pass into the function, as follows:
var selectValues = getSelectValues('id1', 'id2', 'id3');
If a <select> with one of your specified ids does not exist the array contains null for the value for that position.
There are a couple of other ways to do this, you could pass the function an array of id values: getSelectValues([ 'id1', 'id2', 'id3' ]), in which case the function would be changed:
function getSelectValues(ids) {
var values = [];
for (var i = 0; i < ids.length; i++) {
// ...
You could also pass the function a map of ids and populate the values:
var myMap = { 'id1': null, 'id2': null, 'id3': null };
getSelectValues(myMap);
// myMap['id1'] contains the value for id1, etc
This would change the function to be:
function getSelectValues(map) {
for (var id in map) {
var select = document.getElementById(id);
if (select) {
map[id] = select.options[select.selectedIndex].value;
} else {
map[id] = null;
}
}
}
Use a framework like jQuery mentioned above or just do it the old school way. document.getElementById('dropdownId').value .

Categories