JavaScript: get value of dropdown - javascript

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 .

Related

How to loop through an array calling jquery.each on each element?

I am trying to loop through an array of elements and then validate each instance of each element. This is how I am doing it:
var elements = ["h1","h2","h3","h4","p","strong","label","span","a"];
function targetZWS(){
for (var i = 0; i < elements.length; i++) {
var item = $(".page-content "+elements[i]);
$(item).each(function() {
checkElement(this);
});
}
}
This throws a warning that I am creating a function inside a loop, how do I avoid this?
You are trying too hard :) JQuery allows you to enter multiple options in a single selector.
function targetZWS(){
$("h1,h2,h3,h4,p,strong,label,span,a").each(function() {
checkElement(this);
});
}
}
http://api.jquery.com/multiple-selector/
Use .each() to loop through the array as:
$(function() {
var elements = ["h1","h2","h3","h4","p","strong","label","span","a"];
$.each(elements, function(index, value) {
alert(value);
var sel = ".page-content" + value
var item = $("sel");
$(item).each(function() {
checkElement(this);
});
})
})
DEMO

Pass Multiple Select Values to a Javascript API function

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

get the values of the options in the dropdown after moving them from one to another

I have 2 drop downs and I can move the objects from one to another using the buttons. I want to get the updated values after I am done with moving them from one drop down to another. the values in the array is coming out to be null.
How can I get the updated value of all the options in an array. I need to pass the updated values to the controller from one function like function AddFiles(iniIdArray,afterIdArray)
http://jsfiddle.net/678hmujh/1/
var varInitialId = document.getElementById('iniId');
for (i = 0; i < varInitialId.options.length; i++) {
iniIdArray[i] = varInitialId.options[i].value;
}
var varAfterId = document.getElementById('afterId');
for (i = 0; i < varAfterId.options.length; i++) {
afterIdArray[i] = varAfterId.options[i].value;
}
You could use map: http://jsfiddle.net/678hmujh/4/
$('#listButton').on('click', function() {
var first = $('#iniId option').map(function(){ return this.value; });
var second = $('#afterId option').map(function(){ return this.value; });
console.log( first.toArray() );
console.log( second.toArray() );
});
By doing first.toArray() or second.toArray() you can get a basic javascript array of what was built.
$('select#iniId > option').each(function() {
$(this).text(); //is your option text
$(this).val(); //is your option value
});

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/

removing all option of dropdown box in javascript

How can i dynamically remove all options of a drop down box in javascript?
document.getElementById('id').options.length = 0;
or
document.getElementById('id').innerHTML = "";
var select = document.getElementById('yourSelectBox');
while (select.firstChild) {
select.removeChild(select.firstChild);
}
Setting the length to 0 is probably the best way, but you can also do this:
var mySelect = document.getElementById("select");
var len = mySelect.length;
for (var i = 0; i < len; i++) {
mySelect.remove(0);
}
<select id="thing"><option>fdsjl</option></select>
<script>
var el = document.getElementById('thing');
el.innerHTML = '';
// or this
while ( el.firstChild ) {
el.removeChild( el.firstChild )
}
</script>
Its very easy using JavaScript and DOM:
while (selectBox.firstChild)
selectBox.removeChild(selectBox.firstChild);
The fastest solution I was able to find is the following code (taken from this article):
// Fast javascript function to clear all the options in an HTML select element
// Provide the id of the select element
// References to the old <select> object will become invalidated!
// This function returns a reference to the new select object.
function ClearOptionsFast(id)
{
var selectObj = document.getElementById(id);
var selectParentNode = selectObj.parentNode;
var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
selectParentNode.replaceChild(newSelectObj, selectObj);
return newSelectObj;
}
There is simple and elegant way to do this:
for(var o of document.querySelectorAll('#id > option')) {
o.remove()
}

Categories