How to set the selected index of a dropdown using javascript - 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.

Related

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

How to check whether a string is among the `options` of a `select` in jquery?

The html codes are like this:
<select id="select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
I was wondering how to write a function to test whether a string is among the option of a select, such as
test_in("volvo", "select1") // Return True
test_in("asdf", "select1") // Return False
test_in("AUDI", "select1") // Return False
Does anyone have ideas about this? Thanks!
This is how I would do it:
function test_in(value, selector) {
return $(selector + " option[value=" + value + "]").length > 0;
}
fiddle
You might want to convert the casing if you want it to be less strict. Also I'm not sure how you want to handle cases where the option element has a different value attribute and text content. Which one is the deciding one for the test? The version I wrote checks the value attribute.
Note: As pointed out in the comments, the function I wrote takes an entire selector, so you have to include # for ids and . for classes (e.g. #select1 in your case). I think this is the best approach as you aren't forced to use just ids for any select you want to check.
If you want an actual jQuery function for it, here is something you could use. It accepts a regular expression as well as a string to search for in each option's value; only the first element of the jQuery collection is used to search through.
(function($) {
$.fn.hasOption = function(re) {
var options = this[0] && this[0].options || [],
matches = re.test || function(val) {
return val.indexOf(re) != -1;
}
for (var i = 0, item; item = options[i]; ++i) {
if (matches.call(re, item.value)) {
return true;
}
}
return false;
}
}(jQuery));
To call it:
$('#select1').hasOption('volvo')); // true
$('#select1').hasOption('asdf')); // false
$('#select1').hasOption('AUDI')); // false
$('#select1').hasOption(/AUDI/i)); // true!
$("#select1 option[value='volvo']").length - if that equals to zero, you don't have it in the select.
Vanilla JS solution: http://jsfiddle.net/rfQga/2/
var test_in = function(val, target) {
var select = document.getElementById(target),
retVal = false,
rgCheck = new RegExp(val, "g");
var i = 0,
opts = select.options,
l = opts.length;
for (;i<l;i++) {
if (rgCheck.test(opts[i].value)) {
retVal = true;
break;
}
}
return retVal;
}
Try using indexOf on the options array of the select control
Nope, options it's a nodeList, so try:
Try
var opts = [].slice.call(document.querySelector('#select1').options);
if (opts.filter(function(opt){return /mercedes/i.test(opt.value);}).length){
/* ... */
}
Try using something like this:
function test_in(value, selectId){
var foundValue = null;
$("#" + selectId + " > option").each(function() {
if (this.text == value){
foundValue = value;
return false; // break the each iteration
}
});
return (foundValue != null);
}
try this:
$("#select1 > option").each(function() {
if($(this).val()=='volvo'){
alert("value is in the combobox");
}
});​
working demo here

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

Select option removal function

The following function is supposed to remove a selected value from the selectbox,
and update a hidden field with all values.
I have two problems with it:
Lets say I have the following options in the selectbox : 1071,1000,1052
After removing the first option (1071), the hidden field is getting a value of 1052,1000,1000,
if I remove the second option (1000) the hidden field is 1052,1052,1071
if I remove the third one (1052), I get an options[...].value is null or not an object
Can someone plz help me fix this ?
function removeOptions() {
var selectbox = document.getElementById('zipcodes');
var zipcodes = document.getElementById('zip');
var tmpArray = [];
var i;
for (i = selectbox.options.length - 1; i >= 0; i--) {
if (selectbox.options[i].selected){
selectbox.remove(i);
}
tmpArray.push(selectbox.options[i].value);
}
zipcodes.value = tmpArray.join(',');
}
Assuming you don't need the selected value in hidden value, place the portion to push in tmpArray in else part
if (selectbox.options[i].selected){
selectbox.remove(i);
}else{
tmpArray.push(selectbox.options[i].value);
}

Prototype make option in select be selected by provided value

populated by options (country list) using Protype:
for (var i = 0; i < j.length; ++i) {
var opt = new Element('option', {value:j[i].country})
opt.innerHTML = j[i].country_name;
country.appendChild(opt);
}
now i need to make option to be selected by value, somethhing like
function selectByValue(countryCode) {
// make option selected where option value == countryCode
}
how to do it with Prototype?
To answer your question, "ho do you do it with Prototype" more directly, change:
document.getElementById('country').value=countryCode
to...
$('country').value = countryCode;
They both do the same thing, though.
document.getElementById('country').value=countryCode

Categories