Javascript get value from select option based on label - javascript

Using either jQuery or pure JavaScript, how can I get the ID for a select option based on the label? So for example, given the following:
<select id="blah">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
If I have the label "Two" but I need to know the value associated with it, how can I get that value from this select? I don't want to simply select it, I need to know what the value is.

If the only reference you have is really the actual text content, then you'll have to loop through the elements and check the content of each one. Shown here with jQuery just because it's less to type:
var result;
$("option").each(function() {
if ($(this).text() == "Two") {
result = $(this).attr("value");
return false;
});
});

Another option:
$('#blah').find('option:contains("Two")').val();
(Pun intended?)

Get all the options and then use find to get the one with specific text.
const optionEls = Array.from(document.querySelectorAll("#blah option"));
const hasText = text => el => el.textContent === text;
const optionWithTwo = optionEls.find(hasText("Two"));
console.log(optionWithTwo.value);
<select id=blah>
<option value=1>One</option>
<option value=2>Two</option>
<option value=3>Three</option>
</select>

Related

Is there a method to grab whatever is between the option tag?

Lets say I have a select with some options inside it.
<select>
<option value = 1>dog</option>
<option value = 2>cat</option>
<option value = 3>bird</option>
</select>
Is there a way to grab whatever is between the option tag if our value is something different? For instance how to grab 'dog'. 'cat', or 'bird'
EDIT: MORE DESCRIPTION
Select the elements, then do whatever you want with it
document.querySelectorAll('select option').forEach(e =>
console.log(`found option with value: ${e.value} and innerText: ${e.innerText}`)
)
<select>
<option value=1>dog</option>
<option value=2>cat</option>
<option value=3>bird</option>
</select>
You can get the text inside the option tag using jQuery in this way: $("select option").text() - this will return a list ['dog', 'cat', 'bird']
p.s if you want to filter with a specific value, then use: $("select option[value='1']").text()
You could get text from all <option> tags by taking document.getElementsByTagName for the wanted tags.
Array.prototype.forEach.call(
document.getElementsByTagName('option'),
e => console.log(e.text)
);
<select>
<option value = 1>dog</option>
<option value = 2>cat</option>
<option value = 3>bird</option>
</select>
Answered using jquery because i love it
$(document).ready(function(){
$('#dropdown').on('change',function(){
alert($(this).val() + $(this).find(':selected').text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown">
<option value = 1>dog</option>
<option value = 2>cat</option>
<option value = 3>bird</option>
</select>
using javascript , getting selected option's text :
<select onchange="getTextVal(this)">
<option value = 1>dog</option>
<option value = 2>cat</option>
<option value = 3>bird</option>
</select>
And javascript :
function getTextVal(e){
console.log(e.options[e.selectedIndex].text);
}
JsFiddle :

jQuery - Set the selected option of a select box using value or text with options nested in optgroups

So I am writing an app that requires an address input and I have a select element for the user to select the state/province. It needs to support the US and Canada so it has nested optgroups to separate those out and a single, first level option as it's default value. Here is a basic example:
<select name="state" id="state">
<option class="co" value="" data-placeholder="true" disabled selected>Choose your state...</option>
<optgroup label="United States">
<option class="co" value="AL">Alabama</option>
<option class="co" value="AK">Alaska</option>
<option class="co" value="AZ">Arizona</option>
</optgroup>
<optgroup label="Canada">
<option class="co" value="AB">Alberta</option>
<option class="co" value="BC">British Columbia</option>
<option class="co" value="MB">Manitoba</option>
</optgroup>
Now I need to programmatically select the option that matches input from an external source and I want to check for a match based on both the value of the option element or its text. Whichever option is a match would then be set as the selected option. I know you can set the selected option by value using
$("#state").val(myValue)
and I know you can set an option based on text in this way
var myText = "The state I want.";
$("#state").children().filter(function() {
return $(this).text() == myText;
}).prop('selected', true);
Is there a clean way to do this without having to run through each child and checking if it's an optgroup and then running through all its children to check for a match? Is there an easy way through jQuery to combine the value and text methods of setting the selected option?
One other complication, I am going to be doing this within an external jQuery plugin. Within the function I need to modify I have the select element as a variable
$element
so I need a way to do it kind of like this if possible:
$element.descendents(":option").filter(function() {
//do the selecting here
}).prop('selected', true);
If you want to select by the option value, use the value selector:
var myText = "AZ";
$('#state option[value="' + myText + '"]').prop('selected', true);
If you want to search by the option's label, use a filter:
var myText = "Arizona";
$('#state option').filter(function () { return $(this).html() == myText; }).prop('selected', true)
Solved. Since I already had my element passed to a function as a jQuery variable, $element, I couldn't just use the standard selector in the form of:
$("#state option").filter(
// filter function
).prop('selected', true);
After a lot of trying, I got this and it works:
function functionIHadToChange($element, value) {
// other code
$element.find("option").filter(function(){
return ( ($(this).val() == value) || ($(this).text() == value) )
}).prop('selected', true);
}
I am not sure I understood completely your question but I am attempting to answer it in this fiddle
The trick being that you can select it by setting the value of the select box directly
$("#state").val( a_value );
You can set it by $("#select_id").prop("selectedIndex", 3); // Select index starts from zero.
Read here for example this.
$element = $('select#state');
$options = $element.find('option');
$wanted_element = $options.filter(function () {
return $(this).val() == "Alabama" || $(this).text() == "Alabama"
});
$wanted_element.prop('selected', true);
Would be one way to do it.
But i would guess, without knowing the exact internas of the .find() method, in the end jQuery will use at least two loops itself to perform this...
I'm late here but for future visitor, easiest way to do that is :
html
<select name="dept">
<option value="">This doctor belongs to which department?</option>
<option value="1">Orthopaedics</option>
<option value="2">Pathology</option>
<option value="3">ENT</option>
</select>
jQuery
$('select[name="dept"]').val('3');
Output: This will active ENT.

Obtain the number of the item in an options menu?

I'm using .val() in jQuery to retain the value of an options menu onChange.
How would I retain the number (as in as it is ordered) of the item in the drop down using jQuery?
<select>
<option> //option 1
<option> //option 2
</select>
Here is what I have set up now:
<select id="start_month" onChange="getMonthDay()">
<option>Jan</option>
<option>Feb</option>
<option>March</option>
<option>April</option>
<select>
Using,
function getMonthDay()
{
$('#start_month').val()
}
I can get whatever value is selected, but my question is how do I get the Number down of this value in the markup? For March, I would want 3.. and so on
Can you reformulate your question better? I'm still lost in what do you want.
But, nevertheless here is how <select> works in jQuery
<select id="selection">
<option value="val_1">value 1</option>
<option value="val_2">value 2</option>
</select>
$("#selection").val() will give you val_1 or val_2 depending on witch item is currently selected.
If you want to go through all options and check the selected on, you can use
$("#selection option:selected").val();
or itenerate through all <option>'s
$("#selection option").each(function() {
if( $(this).is(":selected") ) {
var v = $(this).val();
}
});
If you want to retain all options you can easily clone them or assign them as data, if you want to keep those values throughout the pages, use Local Database or Cookies to persist the data.
To answer your question after your update:
First: Why don't you have:
<select id="start_month" onChange="getMonthDay()">
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">March</option>
<option value="4">April</option>
<select>
And use the value of the selected item?
Second: Just use what I wrote above and itenerate through the options
$("#start_month option").each(function(index, element) {
if( $(this).is(":selected") ) {
// get index position, remember to add 1 as arrays start at 0
var n = index;
// break each
return false;
}
});
You'd get a list of the <option> elements, find the selected one, and use index:
var $opts = $('#start_month option');
var zero_based_index = $opts.index($opts.filter(':selected'));
Demo: http://jsfiddle.net/ambiguous/HyukW/
Just add 1 if you want a one-based index.
I made something like this,with zero based key ;
<select id='deneme'>
<option>Val1</option>
<option>Val2</option>
<option>Val3</option>
<option>Val4</option>
</select>
$('#deneme').change(function(){
$.each( $('#deneme').children('option'),function(key,value){
if($(this).is(':selected'))
alert(key)
})
})
u can check from here http://jsfiddle.net/8JZCw/
No need for any iteration here, let jQuery do that for you, just get the selected index and increment...
$('#start_month option:selected').index() + 1

javascript function not getting dropdown text

i am using javascript to get the text of selected item from dropdown list.
but i am not getting the text.
i am traversing the dropdown list by name..
my html dropdownlist is as:
<select name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
and my javascript is as:
function div1() {
var select = document.getElementsByName("SomeName");
var result = select.options[select.selectedIndex].text;
alert(result);
}
can you please help me out..
Option 1 - If you're just looking for the value of the selected item, pass it.
<select name="SomeName" onchange="div1(this.value);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(val)
{
alert(val);
}
Option 2 - You could also use the ID as suggested.
<select id="someID" name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1()
{
var ddl = document.getElementById("someID");
var selectedText = ddl.options[ddl.selectedIndex].value;
alert(selectedText);
}
Option 3 - You could also pass the object itself...
<select name="SomeName" onchange="div1(this);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(obj)
{
alert(obj.options[obj.selectedIndex].value);
}
getElementsByName returns an array of items, so you'd need:
var select = document.getElementsByName("SomeName");
var text = select[0].options[select[0].selectedIndex].text;
alert(text);
Or something along those lines.
Edit: instead of the "[0]" bit of code, you probably want either (a) to loop all items in the "select" if you expect many selects with that name, or (b) give the select an id and use document.getElementById() which returns just 1 item.
The problem with the original snippet posted is that document.getElementsByName() returns an array and not a single element.
To fix the original snippet, instead of:
document.getElementsByName("SomeName"); // returns an array
try:
document.getElementsByName("SomeName")[0]; // returns first element in array
EDIT: While that will get you up and running, please note the other great alternative answers here that avoid getElementsByName().

Retrieving the text of the selected <option> in <select> element

In the following:
<select id="test">
<option value="1">Test One</option>
<option value="2">Test Two</option>
</select>
How can I get the text of the selected option (i.e. "Test One" or "Test Two") using JavaScript
document.getElementsById('test').selectedValue returns 1 or 2, what property returns the text of the selected option?
function getSelectedText(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].text;
}
var text = getSelectedText('test');
If you use jQuery then you can write the following code:
$("#selectId option:selected").html();
document.getElementById('test').options[document.getElementById('test').selectedIndex].text;
Under HTML5 you are be able to do this:
document.getElementById('test').selectedOptions[0].text
MDN's documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions indicates full cross-browser support (as of at least December 2017), including Chrome, Firefox, Edge and mobile browsers, but excluding Internet Explorer.
selectElement.options[selectElement.selectedIndex].text;
References:
options collection, selectedIndex property: HTML DOM Select Object
text property: HTML DOM Option Object
exactly the answer of this question: Option text Property
The options property contains all the <options> - from there you can look at .text
document.getElementById('test').options[0].text == 'Text One'
You can use selectedIndex to retrieve the current selected option:
el = document.getElementById('elemId')
selectedText = el.options[el.selectedIndex].text
this.options[this.selectedIndex].innerText
If you found this thread and wanted to know how to get the selected option text via event here is sample code:
alert(event.target.options[event.target.selectedIndex].text);
Use the select list object, to identify its own selected options index.
From there - grab the inner HTML of that index.
And now you have the text string of that option.
<select onchange="alert(this.options[this.selectedIndex].innerHTML);">
<option value="">Select Actions</option>
<option value="1">Print PDF</option>
<option value="2">Send Message</option>
<option value="3">Request Review</option>
<option value="4">Other Possible Actions</option>
</select>
The :checked selector can be used with document.querySelector to retrieve the selected option.
let selectedText = document.querySelector('#selectId option:checked').text;
// or
let selectedText = document.querySelector('#selectId')
.querySelector('option:checked').text;
document.querySelector('button').addEventListener('click', function(e) {
console.log(document.querySelector('#selectId option:checked').text);
});
<select id="selectId">
<option>a</option>
<option>b</option>
<option>c</option>
</select>
<button>
Get selected text
</button>
For select elements with the multiple attribute, document.querySelectorAll can be used to obtain all selected options.
let selectedText = [...document.querySelectorAll('#selectId option:checked')]
.map(o => o.text);
document.querySelector('button').addEventListener('click', function(e) {
let selectedText = [...document.querySelectorAll('#selectId option:checked')]
.map(o => o.text);
console.log(selectedText);
});
<select id="selectId" multiple>
<option>a</option>
<option>b</option>
<option>c</option>
</select>
<button>
Get selected text
</button>
Similar to #artur just without jQuery, with plain javascript:
// Using #Sean-bright's "elt" variable
var selection=elt.options[elt.selectedIndex].innerHTML;
Easy, simple way:
const select = document.getElementById('selectID');
const selectedOption = [...select.options].find(option => option.selected).text;
It is pretty simple. In javascript anything with an ID doesn't need document.queryselector or $('#test') you can just use test. Then you simply loop over the selectedOptions which is apart of javascript and you can add it to a new array and use that data how ever you want.
let selectedItems = [];
for ( var i = 0; i < test.selectedOptions.length; i++) {
selectedItems.push(test.selectedOptions[i].text);
}
Also
// if you want values
selectedItems.push(test.selectedOptions[i].value);

Categories

Resources