All right, say I have this:
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()
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();
Use:
function selected_state(){
jQuery("#list option").each(function(){
if(jQuery(this).val() == "2"){
jQuery(this).attr("selected","selected");
return false;
}
});
}
jQuery(document).ready(function(){
selected_state();
});
$("#list option:selected").each(function() {
alert($(this).text());
});
for multiple selected value in the #list
element.
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.
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