how do I get the text instead of the value - javascript

I have this HTML:
<select class="business_types_select" name="business_type_id">
<option value="0" selected="selected">Select a Business Type</option>
<option value="54">Bakery</option>
<option value="55">Tobacco</option>
</select>
and if I select Bakery and then try:
$(".business_types_select").val()
I get 54, but how do i get the text Bakery? If I try
$(".business_types_select").text()
I get:
" Select a Business Type Bakery Tobacco "

Try:
$(".business_types_select :selected").text()
Without this, the .text() is behaving like it should, which is to bring back all of the text from that particular class. Adding :selected to the selector narrows it down to just the one you have selected.
Remember to cache your selectors if you're going to be operating on them often for performance.

You have to reduce the selector to the selection option:
$(".business_types_select").find('option:selected').text();

Like this:
$(".business_types_select > option:selected").text()
(In the short example here I have assumed that there is only one <select class="business_types_select" />. My jsfiddle example is more comprehensive.)

$(".business_types_select option:selected").text()
That will return the text of the selected option only

$(".business_types_select").find('option:selected').text();

Related

click specific option using javascript or jquery

I tried googling this but I am getting only on event trigger searches instead of what I am looking for.
I want to dynamically click on any of the options in the select dropdown by using the value or the text if possible.
HTML
<select id="certainspamselectid" name="certainspamselect" style="margin-left: 165px;">
<option value="0">permanently deleted</option>
<option value="4">moved to admin quarantine</option>
<option value="1">moved to junk email folder</option>
<option value="5">delivered to inbox with tag</option>
<option value="2">delivered to inbox</option>
</select>
I am not sure if I need to use something with $("#certainspamselectid").click..... but I am not sure what to use after click. I would have tried more things but my google searches keep pinpointing me for on event triggers when I just want to click on one of these options using either JS or jQuery.
I have read your problem and honestly, I can't understand what you want exactly.
However, it looks like you want to select some certain option of the select dropdown.
If that's right, you don't need to call some kind of click function.
You can do it easily with jQuery.
For example, imagine that you are going to select third option - "moved to junk email folder". Then you can select it by code like below.
$("#certainspamselectid").val(1);
If my answer is not enough for you, let me know detail of your problem.
With <select> what you need is .change instead of .click
Here is a quick example .. change the $value and check again
$("#certainspamselectid").on('change' , function(){
console.log("Value Changed To: "+$(this).val());
if($(this).val() == 5){
console.log("value 5 is selected");
}
});
let $value = 4;
$("#certainspamselectid").val($value).change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="certainspamselectid" name="certainspamselect" style="margin-left: 165px;">
<option value="0">permanently deleted</option>
<option value="4">moved to admin quarantine</option>
<option value="1">moved to junk email folder</option>
<option value="5">delivered to inbox with tag</option>
<option value="2">delivered to inbox</option>
</select>
why don't you simply change the value of the select like this
$("#certainspamselectid").val(4)
It will automatically show the text from the selected option
I don't think that clicking on an option would help you

Need Help to Scrape a Website [duplicate]

I have a drop-down list with known values. What I'm trying to do is set the drop down list to a particular value that I know exists using jQuery.
Using regular JavaScript, I would do something like:
ddl = document.getElementById("ID of element goes here");
ddl.value = 2; // 2 being the value I want to set it too.
However, I need to do this with jQuery, because I'm using a CSS class for my selector (stupid ASP.NET client ids...).
Here are a few things I've tried:
$("._statusDDL").val(2); // Doesn't find 2 as a value.
$("._statusDDL").children("option").val(2) // Also failed.
How can I do it with jQuery?
Update
So as it turns out, I had it right the first time with:
$("._statusDDL").val(2);
When I put an alert just above it works fine, but when I remove the alert and let it run at full speed, I get the error
Could not set the selected property. Invalid Index
I'm not sure if it's a bug with jQuery or Internet Explorer 6 (I'm guessing Internet Explorer 6), but it's terribly annoying.
jQuery's documentation states:
[jQuery.val] checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.
This behavior is in jQuery versions 1.2 and above.
You most likely want this:
$("._statusDDL").val('2');
Add .change() to see the option in the dropdown list frontend:
$("._statusDDL").val('2').change();
With hidden field you need to use like this:
$("._statusDDL").val(2);
$("._statusDDL").change();
or
$("._statusDDL").val(2).change();
These solutions seem to assume that each item in your drop down lists has a val() value relating to their position in the drop down list.
Things are a little more complicated if this isn't the case.
To read the selected index of a drop down list, you would use this:
$("#dropDownList").prop("selectedIndex");
To set the selected index of a drop down list, you would use this:
$("#dropDownList").prop("selectedIndex", 1);
Note that the prop() feature requires JQuery v1.6 or later.
Let's see how you would use these two functions.
Supposing you had a drop down list of month names.
<select id="listOfMonths">
<option id="JAN">January</option>
<option id="FEB">February</option>
<option id="MAR">March</option>
</select>
You could add a "Previous Month" and "Next Month" button, which looks at the currently selected drop down list item, and changes it to the previous/next month:
<button id="btnPrevMonth" title="Prev" onclick="btnPrevMonth_Click();return false;" />
<button id="btnNextMonth" title="Next" onclick="btnNextMonth_Click();return false;" />
And here's the JavaScript which these buttons would run:
function btnPrevMonth_Click() {
var selectedIndex = $("#listOfMonths").prop("selectedIndex");
if (selectedIndex > 0) {
$("#listOfMonths").prop("selectedIndex", selectedIndex - 1);
}
}
function btnNextMonth_Click() {
// Note: the JQuery "prop" function requires JQuery v1.6 or later
var selectedIndex = $("#listOfMonths").prop("selectedIndex");
var itemsInDropDownList = $("#listOfMonths option").length;
// If we're not already selecting the last item in the drop down list, then increment the SelectedIndex
if (selectedIndex < (itemsInDropDownList - 1)) {
$("#listOfMonths").prop("selectedIndex", selectedIndex + 1);
}
}
My site is also useful for showing how to populate a drop down list with JSON data:
http://mikesknowledgebase.com/pages/Services/WebServices-Page8.htm
Just an FYI, you don't need to use CSS classes to accomplish this.
You can write the following line of code to get the correct control name on the client:
$("#<%= statusDDL.ClientID %>").val("2");
ASP.NET will render the control ID correctly inside the jQuery.
Just try with
$("._statusDDL").val("2");
and not with
$("._statusDDL").val(2);
After looking at some solutions, this worked for me.
I have one drop-down list with some values and I want to select the same value from another drop-down list... So first I put in a variable the selectIndex of my first drop-down.
var indiceDatos = $('#myidddl')[0].selectedIndex;
Then, I select that index on my second drop-down list.
$('#myidddl2')[0].selectedIndex = indiceDatos;
Note:
I guess this is the shortest, reliable, general and elegant solution.
Because in my case, I'm using selected option's data attribute instead of value attribute.
So if you do not have unique value for each option, above method is the shortest and sweet!!
I know this is a old question and the above solutions works fine except in some cases.
Like
<select id="select_selector">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3">Item3</option>
<option value="4" selected="selected">Item4</option>
<option value="5">Item5</option>
</select>
So Item 4 will show as "Selected" in the browser and now you want to change the value as 3 and show "Item3" as selected instead of Item4.So as per the above solutions,if you use
jQuery("#select_selector").val(3);
You will see that Item 3 as selected in browser.But when you process the data either in php or asp , you will find the selected value as "4".The reason is that , your html will look like this.
<select id="select_selector">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3" selected="selected">Item3</option>
<option value="4" selected="selected">Item4</option>
<option value="5">Item5</option>
</select>
and it gets the last value as "4" in sever side language.
SO MY FINAL SOLUTION ON THIS REGARD
newselectedIndex = 3;
jQuery("#select_selector option:selected").removeAttr("selected");
jQuery("#select_selector option[value='"+newselectedIndex +"']").attr('selected', 'selected');
EDIT: Add single quote around "+newselectedIndex+" so that the same functionality can be used for non-numerical values.
So what I do is actually ,removed the selected attribute and then make the new one as selected.
I would appreciate comments on this from senior programmers like #strager , #y0mbo , #ISIK and others
If we have a dropdown with a title of "Data Classification":
<select title="Data Classification">
<option value="Top Secret">Top Secret</option>
<option value="Secret">Secret</option>
<option value="Confidential">Confidential</option>
</select>
We can get it into a variable:
var dataClsField = $('select[title="Data Classification"]');
Then put into another variable the value we want the dropdown to have:
var myValue = "Top Secret"; // this would have been "2" in your example
Then we can use the field we put into dataClsField, do a find for myValue and make it selected using .prop():
dataClsField.find('option[value="'+ myValue +'"]').prop('selected', 'selected');
Or, you could just use .val(), but your selector of . can only be used if it matches a class on the dropdown, and you should use quotes on the value inside the parenthesis, or just use the variable we set earlier:
dataClsField.val(myValue);
So I changed it so that now it
executes after a 300 miliseconds using
setTimeout. Seems to be working now.
I have run into this many times when loading data from an Ajax call. I too use .NET, and it takes time to get adjusted to the clientId when using the jQuery selector. To correct the problem that you're having and to avoid having to add a setTimeout property, you can simply put "async: false" in the Ajax call, and it will give the DOM enough time to have the objects back that you are adding to the select. A small sample below:
$.ajax({
type: "POST",
url: document.URL + '/PageList',
data: "{}",
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var pages = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#locPage' + locId).find('option').remove();
$.each(pages, function () {
$('#locPage' + locId).append(
$('<option></option>').val(this.PageId).html(this.Name)
);
});
}
});
I use an extend function to get client ids, like so:
$.extend({
clientID: function(id) {
return $("[id$='" + id + "']");
}
});
Then you can call ASP.NET controls in jQuery like this:
$.clientID("_statusDDL")
Another option is to set the control param ClientID="Static" in .net and then you can access the object in JQuery by the ID you set.
<asp:DropDownList id="MyDropDown" runat="server" />
Use $("select[name$='MyDropDown']").val().
Just a note - I've been using wildcard selectors in jQuery to grab items that are obfuscated by ASP.NET Client IDs - this might help you too:
<asp:DropDownList id="MyDropDown" runat="server" />
$("[id* = 'MyDropDown']").append("<option value='-1'> </option>"); //etc
Note the id* wildcard- this will find your element even if the name is "ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$MyDropDown"
How are you loading the values into the drop down list or determining which value to select? If you are doing this using Ajax, then the reason you need the delay before the selection occurs could be because the values were not loaded in at the time that the line in question executed. This would also explain why it worked when you put an alert statement on the line before setting the status since the alert action would give enough of a delay for the data to load.
If you are using one of jQuery's Ajax methods, you can specify a callback function and then put $("._statusDDL").val(2); into your callback function.
This would be a more reliable way of handling the issue since you could be sure that the method executed when the data was ready, even if it took longer than 300 ms.
<asp:DropDownList ID="DropUserType" ClientIDMode="Static" runat="server">
<asp:ListItem Value="1" Text="aaa"></asp:ListItem>
<asp:ListItem Value="2" Text="bbb"></asp:ListItem>
</asp:DropDownList>
ClientIDMode="Static"
$('#DropUserType').val('1');
In my case I was able to get it working using the .attr() method.
$("._statusDDL").attr("selected", "");
Pure JS
For modern browsers using CSS selectors is not a problem for pure JS
document.querySelector('._statusDDL').value = 2;
function change() {
document.querySelector('._statusDDL').value = 2;
}
<select class="_statusDDL">
<option value="1" selected>A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<button onclick="change()">Change</button>
If we want to find from the option name and then selected options with the jQuery please see below code:-
<div class="control">
<select name="country_id" id="country" class="required-entry" title="Country" data-validate="{'validate-select':true}" aria-required="true">
<option value=""> </option>
<option value="SA">Saudi Arabia</option>
<option value="AF">Afghanistan</option>
<option value="AR">Argentina</option>
<option value="AM">Armenia</option>
<option value="AW">Aruba</option>
<option value="AU">Australia</option>
<option value="AT">Austria</option>
<option value="IS">Iceland</option>
<option value="IN">India</option>
<option value="ID">Indonesia</option>
<option value="IR">Iran</option>
<option value="IQ">Iraq</option>
<option value="IE">Ireland</option>
<option value="IM">Isle of Man</option>
<option value="IL">Israel</option>
<option value="IT">Italy</option>
<option value="JM">Jamaica</option>
<option value="JP">Japan</option>
<option value="JE">Jersey</option>
<option value="JO">Jordan</option>
<option value="AE">United Arab Emirates</option>
<option value="GB">United Kingdom</option>
<option value="US" selected="selected">United States</option>
</select>
</div>
<script type='text/javascript'>
let countryRegion="India";
jQuery("#country option:selected").removeAttr("selected");
let cValue= jQuery("#country option:contains("+countryRegion+")").val();
jQuery("#country option[value='"+cValue +"']").attr('selected', 'selected');
</script>
I hope this will help!

get the text value in the dropdown with class

how to get the selected text of the option.
<select class="float-left groupNames" name="Group">
<option value="preview[object Object]0">test</option>
<option value="preview[object Object]1">test1</option>
<option value="preview[object Object]2">test2</option>
</select>
I tried $(".groupNames option:selected").text();
but its not the right value. so I am getting testtest2 if I am selecting the third option.
$(".groupNames").val() is all you need.
jsFiddle example
However if you have multiple .groupNames elements, you'll need to be more specific with the selector.
$(".groupNames option:selected").text(); as you probably saw, will get the selected option's text, not the select's value.
hi please add an id to easily access the select here is an tested fiddle http://jsfiddle.net/elviz/259m3qkb/1/
$("#newSkill").change(function(){
var kamote = document.getElementById("newSkill").options[document.getElementById('newSkill').selectedIndex].text;
alert(kamote);
});

How to alert the selected option using javascript or jquery?

I am using a select tag in my code, here is my code,
<select onchange="test(this);">
<option value="0">Select</option>
<option value="1">Select1</option>
<option value="2">Select2</option>
<option value="3">Select3</option>
</select>
and javascript code is here,
<script>
function test(obj)
{
alert($(obj).val());
}
</script>
I want to alert the selected text here, If I use the above code the value of the selected option is coming, but I want to alert the text of the selected option can anyone tell to achive this one.
I want to alert it without using any class or id.
I want to alert it only through the obj.
I am waiting for your help.
Thanks In advance
This should do the trick...
alert($(obj).find("option:selected").text());
That uses the jQuery object $(obj), like you already had, but does a find() which searches the child elements, in this case the selected option.
jQuery find()
:selected pseudo-selector
Try this..
alert($(obj).find("option:selected").text());
you can try this:
alert($(obj).find('option').eq(obj.value).text());
Working jsFiddle
<select id="someid" onchange="test();">
<option value="0">Select</option>
<option value="1">Select1</option>
<option value="2">Select2</option>
<option value="3">Select3</option>
</select>
javascript>
function test(){
var elem = document.getElementById("someid"),
var selectedNode = elem.options[elem.selectedIndex].text;
alert(selectedNode );
}
jQuery>
$("#someid").change(){
alert($(this).find("option:selected").text());
}

jQuery get specific option tag text

All right, say I have this:
<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>
What would the selector look like if I wanted to get "Option B" when I have the value '2'?
Please note that this is not asking how to get the selected text value, but just any one of them, whether selected or not, depending on the value attribute. I tried:
$("#list[value='2']").text();
But it is not working.
If you'd like to get the option with a value of 2, use
$("#list option[value='2']").text();
If you'd like to get whichever option is currently selected, use
$("#list option:selected").text();
It's looking for an element with id list which has a property value equal to 2.
What you want is the option child of the list:
$("#list option[value='2']").text()
This worked perfectly for me, I was looking for a way to send two different values with options generated by MySQL, and the following is generic and dynamic:
$(this).find("option:selected").text();
As mentioned in one of the comments. With this I was able to create a dynamic function that works with all my selection boxes that I want to get both values, the option value and the text.
Few days ago I noticed that when updating the jQuery from 1.6 to 1.9 of the site I used this code, this stop working... probably was a conflict with another piece of code... anyway, the solution was to remove option from the find() call:
$(this).find(":selected").text();
That was my solution... use it only if you have any problem after updating your jQuery.
Based on the original HTML posted by Paolo I came up with the following.
$("#list").change(function() {
alert($(this).find("option:selected").text()+' clicked!');
});
It has been tested to work on Internet Explorer and Firefox.
$("#list option:selected").each(function() {
alert($(this).text());
});
for multiple selected value in the #list element.
If there is only one select tag in on the page then you can specify select inside of id 'list'
jQuery("select option[value=2]").text();
To get selected text
jQuery("select option:selected").text();
Try the following:
$("#list option[value=2]").text();
The reason why your original snippet wasn't working is because your OPTION tags are children to your SELECT tag, which has the id list.
This is an old Question which has not been updated in some time the correct way to do this now would be to use
$("#action").on('change',function() {
alert($(this).find("option:selected").text()+' clicked!');
});
I hope this helps :-)
I wanted to get the selected label. This worked for me in jQuery 1.5.1.
$("#list :selected").text();
$(this).children(":selected").text()
You can get selected option text by using function .text();
you can call the function like this :
jQuery("select option:selected").text();
$("#list [value='2']").text();
leave a space after the id selector.
While "looping" through dynamically created select elements with a .each(function()...): $("option:selected").text(); and $(this + " option:selected").text() did not return the selected option text - instead it was null.
But Peter Mortensen's solution worked:
$(this).find("option:selected").text();
I do not know why the usual way does not succeed in a .each() (probably my own mistake), but thank you, Peter. I know that wasn't the original question, but am mentioning it "for newbies coming through Google."
I would have started with $('#list option:selected").each() except I needed to grab stuff from the select element as well.
Use:
function selected_state(){
jQuery("#list option").each(function(){
if(jQuery(this).val() == "2"){
jQuery(this).attr("selected","selected");
return false;
}else
jQuery(this).removeAttr("selected","selected"); // For toggle effect
});
}
jQuery(document).ready(function(){
selected_state();
});
I was looking for getting val by internal field name instead of ID and came from google to this post which help but did not find the solution I need, but I got the solution and here it is:
So this might help somebody looking for selected value with field internal name instead of using long id for SharePoint lists:
var e = $('select[title="IntenalFieldName"] option:selected').text();
A tip: you can use below code if your value is dynamic:
$("#list option[value='"+aDynamicValue+"']").text();
Or (better style)
$("#list option").filter(function() {
return this.value === aDynamicValue;
}).text();
As mentioned in jQuery get specific option tag text and placing dynamic variable to the value
I needed this answer as I was dealing with a dynamically cast object, and the other methods here did not seem to work:
element.options[element.selectedIndex].text
This of course uses the DOM object instead of parsing its HTML with nodeValue, childNodes, etc.
As an alternative solution, you can also use a context part of jQuery selector to find <option> element(s) with value="2" inside the dropdown list:
$("option[value='2']", "#list").text();
I wanted a dynamic version for select multiple that would display what is selected to the right (wish I'd read on and seen $(this).find... earlier):
<script type="text/javascript">
$(document).ready(function(){
$("select[showChoices]").each(function(){
$(this).after("<span id='spn"+$(this).attr('id')+"' style='border:1px solid black;width:100px;float:left;white-space:nowrap;'> </span>");
doShowSelected($(this).attr('id'));//shows initial selections
}).change(function(){
doShowSelected($(this).attr('id'));//as user makes new selections
});
});
function doShowSelected(inId){
var aryVals=$("#"+inId).val();
var selText="";
for(var i=0; i<aryVals.length; i++){
var o="#"+inId+" option[value='"+aryVals[i]+"']";
selText+=$(o).text()+"<br>";
}
$("#spn"+inId).html(selText);
}
</script>
<select style="float:left;" multiple="true" id="mySelect" name="mySelect" showChoices="true">
<option selected="selected" value=1>opt 1</option>
<option selected="selected" value=2>opt 2</option>
<option value=3>opt 3</option>
<option value=4>opt 4</option>
</select>
You can get one of following ways
$("#list").find('option').filter('[value=2]').text()
$("#list").find('option[value=2]').text()
$("#list").children('option[value=2]').text()
$("#list option[value='2']").text()
$(function(){
console.log($("#list").find('option').filter('[value=2]').text());
console.log($("#list").find('option[value=2]').text());
console.log($("#list").children('option[value=2]').text());
console.log($("#list option[value='2']").text());
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>
Try this:
jQuery("#list option[value='2']").text()
Try
[...list.options].find(o=> o.value=='2').text
let text = [...list.options].find(o=> o.value=='2').text;
console.log(text);
<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>

Categories

Resources