How to show selected option in textbox in C# [duplicate] - javascript

How can I get the selected text (not the selected value) from a drop-down list in jQuery?

$("#yourdropdownid option:selected").text();

Try this:
$("#myselect :selected").text();
For an ASP.NET dropdown you can use the following selector:
$("[id*='MyDropDownId'] :selected")

The answers posted here, for example,
$('#yourdropdownid option:selected').text();
didn't work for me, but this did:
$('#yourdropdownid').find('option:selected').text();
It is possibly an older version of jQuery.

If you already have the dropdownlist available in a variable, this is what works for me:
$("option:selected", myVar).text()
The other answers on this question helped me, but ultimately the jQuery forum thread $(this + "option:selected").attr("rel") option selected is not working in IE helped the most.
Update: fixed the above link

This works for me
$("#dropdownid").change(function() {
alert($(this).find("option:selected").text());
});
If the element created dynamically
$(document).on("change", "#dropdownid", function() {
alert($(this).find("option:selected").text());
});

$("option:selected", $("#TipoRecorde")).text()

$("#DropDownID").val() will give the selected index value.

This works for me:
$('#yourdropdownid').find('option:selected').text();
jQuery version: 1.9.1

For the text of the selected item, use:
$('select[name="thegivenname"] option:selected').text();
For the value of the selected item, use:
$('select[name="thegivenname"] option:selected').val();

Use this
const select = document.getElementById("yourSelectId");
const selectedIndex = select.selectedIndex;
const selectedValue = select.value;
const selectedText = select.options[selectedIndex].text;
Then you get your selected value and text inside selectedValue and selectedText.

Various ways
1. $("#myselect option:selected").text();
2. $("#myselect :selected").text();
3. $("#myselect").children(":selected").text();
4. $("#myselect").find(":selected").text();

$("#dropdownID").change(function(){
alert($('option:selected', $(this)).text());
});

var someName = "Test";
$("#<%= ddltest.ClientID %>").each(function () {
$('option', this).each(function () {
if ($(this).text().toLowerCase() == someName) {
$(this).attr('selected', 'selected')
};
});
});
That will help you to get right direction. Above code is fully tested if you need further help let me know.

For those who are using SharePoint lists and don't want to use the long generated id, this will work:
var e = $('select[title="IntenalFieldName"] option:selected').text();

$("#selectID option:selected").text();
Instead of #selectID you can use any jQuery selector, like .selectClass using class.
As mentioned in the documentation here.
The :selected selector works for <option> elements. It does not work for checkboxes or radio inputs; use :checked for them.
.text() As per the documentation here.
Get the combined text contents of each element in the set of matched elements, including their descendants.
So you can take text from any HTML element using the .text() method.
Refer the documentation for a deeper explanation.

This code worked for me.
$("#yourdropdownid").children("option").filter(":selected").text();

$("select[id=yourDropdownid] option:selected").text()
This works fine

$('#id').find('option:selected').text();

For getting selected value use
$('#dropDownId').val();
and for getting selected item text use this line:
$("#dropDownId option:selected").text();

Select Text and selected value on dropdown/select change event in jQuery
$("#yourdropdownid").change(function() {
console.log($("option:selected", this).text()); //text
console.log($(this).val()); //value
})

Try:
$var = jQuery("#dropdownid option:selected").val();
alert ($var);
Or to get the text of the option, use text():
$var = jQuery("#dropdownid option:selected").text();
alert ($var);
More Info:
http://api.jquery.com/val/
http://api.jquery.com/text/

Simply try the following code.
var text= $('#yourslectbox').find(":selected").text();
it returns the text of the selected option.

var e = document.getElementById("dropDownId");
var div = e.options[e.selectedIndex].text;

$("#dropdown").find(":selected").text();
$("#dropdown :selected").text();
$("#dropdown option:selected").text();
$("#dropdown").children(":selected").text();

Use:
('#yourdropdownid').find(':selected').text();

the following worked for me:
$.trim($('#dropdownId option:selected').html())

This work for me:
$("#city :selected").text();
I'm using jQuery 1.10.2

In sibling case
<a class="uibutton confirm addClient" href="javascript:void(0);">ADD Client</a>
<input type="text" placeholder="Enter client name" style="margin: 5px;float: right" class="clientsearch large" />
<select class="mychzn-select clientList">
<option value="">Select Client name....</option>
<option value="1">abc</option>
</select>
/*jQuery*/
$(this).siblings('select').children(':selected').text()

$(function () {
alert('.val() = ' + $('#selectnumber').val() + ' AND html() = ' + $('#selectnumber option:selected').html() + ' AND .text() = ' + $('#selectnumber option:selected').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<select id="selectnumber">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</div>
</form>
</body>
</html>

Try
dropdown.selectedOptions[0].text
function read() {
console.log( dropdown.selectedOptions[0].text );
}
<select id="dropdown">
<option value="1">First</option>
<option value="2">Second</option>
</select>
<button onclick="read()">read</button>

Related

How to get the current selected value on select dropdown? And how to pass it on a php variable? [duplicate]

How can I get the selected value of a dropdown box using jQuery?
I tried using
var value = $('#dropDownId').val();
and
var value = $('select#dropDownId option:selected').val();
but both return an empty string.
For single select dom elements, to get the currently selected value:
$('#dropDownId').val();
To get the currently selected text:
$('#dropDownId :selected').text();
var value = $('#dropDownId:selected').text()
Should work fine, see this example:
$(document).ready(function(){
$('#button1').click(function(){
alert($('#combo :selected').text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="combo">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
</select>
<input id="button1" type="button" value="Click!" />
Try this jQuery,
$("#ddlid option:selected").text();
or this javascript,
var selID=document.getElementById("ddlid");
var text=selID.options[selID.selectedIndex].text;
If you need to access the value and not the text then try using val() method instead of text().
Check out the below fiddle links.
Demo1 | Demo2
try this
$("#yourDropdown option:selected").text();
I know this is a terribly old post and I should probably be flogged for this pitiful resurrection, but I thought I would share a couple of VERY helpful little JS snippets that I use throughout every application in my arsenal...
If typing out:
$("#selector option:selected").val() // or
$("#selector option:selected").text()
is getting old, try adding these little crumpets to your global *.js file:
function soval(a) {
return $('option:selected', a).val();
}
function sotext(a) {
return $('option:selected', a).text();
}
and just write soval("#selector"); or sotext("#selector"); instead! Get even fancier by combining the two and returning an object containing both the value and the text!
function so(a) {
my.value = $('option:selected', a).val();
my.text = $('option:selected', a).text();
return my;
}
It saves me a ton of precious time, especially on form-heavy applications!
This will alert the selected value.
JQuery Code...
$(document).ready(function () {
$("#myDropDown").change(function (event) {
alert("You have Selected :: "+$(this).val());
});
});
HTML Code...
<select id="myDropDown">
<option>Milk</option>
<option>Egg</option>
<option>Bread</option>
<option>Fruits</option>
</select>
this will do the trick
$('#dropDownId').val();
Yet another tested example:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$('#bonus').change(function() {
alert($("#bonus option:selected").text());
});
});
</script>
</head>
<body>
<select id="bonus">
<option value="1">-$5000</option>
<option value="2">-$2500</option>
<option value="3">$0</option>
<option value="4">$1</option>
<option value="5">We really appreciate your work</option>
</select>
</body>
</html>
Try this, it gets the value:
$('select#myField').find('option:selected').val();
function fundrp(){
var text_value = $("#drpboxid option:selected").text();
console.log(text_value);
var val_text = $("#drpboxid option:selected").val();
console.log(val_text);
var value_text = $("#drpboxid option:selected").attr("value") ;
console.log(value_text);
var get_att_value = $("#drpboxid option:selected").attr("id")
console.log(get_att_value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="drpboxid">
<option id="1_one" value="one">one</option>
<option id="2_two" value="two">two</option>
<option id="3_three" value="three">three</option>
</select>
<button id="btndrp" onclick="fundrp()">Tracking Report1234</button>
Did you supply your select-element with an id?
<select id='dropDownId'> ...
Your first statement should work!
use
$('#dropDownId').find('option:selected').val()
This should work :)
For selected text use:
value: $('#dropDownId :selected').text();
For selected value use:
value: $('#dropDownId').val();
The id that got generated for your drop down control in the html will be dynamic one. So use the complete id $('ct100_<Your control id>').val(). It will work.
I know this is old but I though I update this with an more up to date answer
$( document ).on( 'change', '#combo', function () {
var prepMin= $("#combo option:selected").val();
alert(prepMin);
});
I hope this helps
Or if you would try :
$("#foo").find("select[name=bar]").val();
I used It today and It working fine.
To get the jquery value from drop down you just use below function just sent id and get the selected value:
function getValue(id){
var value = "";
if($('#'+id)[0]!=undefined && $('#'+id)[0]!=null){
for(var i=0;i<$('#'+id)[0].length;i++){
if($('#'+id)[0][i].selected == true){
if(value != ""){
value = value + ", ";
}
value = value + $('#'+id)[0][i].innerText;
}
}
}
return value;
}
Try this:
$('#dropDownId option').filter(':selected').text();
$('#dropDownId option').filter(':selected').val();
You can do this by using following code.
$('#dropDownId').val();
If you want to get the selected value from the select list`s options. This will do the trick.
$('#dropDownId option:selected').text();
$("select[id$=dropDownId]").val()
try this
use either of these codes
$('#dropDownId :selected').text();
OR
$('#dropDownId').text();
This is what works
var value= $('option:selected', $('#dropDownId')).val();
$("#selector <b>></b> option:selected").val()
Or
$("#selector <b>></b> option:selected").text()
Above codes worked well for me
You can use any of these:
$(document).on('change', 'select#dropDownId', function(){
var value = $('select#dropDownId option:selected').text();
//OR
var value = $(this).val();
});
You need to put like this.
$('[id$=dropDownId] option:selected').val();
Use the method below to get the selected value on page load:
$(document).ready(function () {
$('#ddlid').on('change', function () {
var value = $('#ddlid :selected').text();
alert(value);`
});
});
If you have more than one dropdown try:
HTML:
<select id="dropdown1" onchange="myFunction(this)">
<option value='...'>Option1
<option value='...'>Option2
</select>
<select id="dropdown2" onchange="myFunction(this)">
<option value='...'>Option1
<option value='...'>Option2
</select>
JavaScript:
function myFunction(sel) {
var selected = sel.value;
}
HTML:
<select class="form-control" id="SecondSelect">
<option>5<option>
<option>10<option>
<option>20<option>
<option>30<option>
</select>
JavaScript:
var value = $('#SecondSelect')[0].value;
For Normal Page loaded dropdowns
$("#dropDownId").on('change',function(){
var value=$(this).val();
alert(value);
});
for dynamically added options Make sure to keep the id unique
$(document).on('change','#dropDownId',function(){
var value=$(this).val();
alert(value)
});
Using below line of code we can get the dropdownList value .this will work
var getValue = document.getElementById("<%=ddlID.ClientID%>").value;

jQuery SELECT with Textarea

Just wondering if someone can help me on a problem, I don't fully undersand why it doesn't work.
I have this fiddle, http://jsfiddle.net/uomt99zp/
What it is doing:
When you select from the drop down box, insert that word into the textarea.
Which it DOES, when the textarea isn't "touched".
If you type something into the box, and then try to select an item, it doesn't work.
I'm not sure why this doesn't update the textarea. Perhaps someone can shed some light on this issue?
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
You need to set value using .val():
$('.template').val($('.template').val()+text);
Working Demo 1
Also .val() can have callback function which can be used for setting a new value:
function
Type: Function( Integer index, String value ) => String
A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
$('.template').val(function(i,v){ return v+ text});
Working Demo 2
You can try val(function) with old value + new text to append,
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').val(function(ind,val){
return val+text;
});
});
Live Demo
To answer to the "why" it does not work, it's because, the contents of a textarea represent its default value. So, when you append an element to the textarea, you change the default value of this textarea.
So it changes the textarea as long as you did not type in. Once you typed in, the default value is no more used, even if you remove all the text of the textarea.
By using .append you are just concatinating your output string if you want only the dropdown element it would be better to use the .text() or .val() method
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
var existing=$('.template').val();
$('.template').val(existing+text);
});
.append(), .html() and .text() methods do not work with form elements, for setting/getting value of a from element .val() method should be used instead:
Your code is working ...i tried it in visual studio .... Only change I had made is I kept the script under the option control... I am not sure about.for me its working fine.
<body >
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
<script type="text/javascript">
$('.templatesAvailableFields').on('change', function () {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
</script>
</body>
You should control input value's with val() method
// cache element
var $select = $('.templatesAvailableFields');
$select.change( function() {
$('.template').val($select[0].value);
});
just replace append with text
here is the updated fiddle
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').text($('.template').text() + text);
// $('.template').val(text); this won't work in IE <= 7
});
http://jsfiddle.net/rrehan/uomt99zp/2/

Get attributes values from select2 selected option

I'm using the Select2 plugin from http://ivaynberg.github.io/select2/select2-latest.html what works fine but i'm having a problem to get the values from the options attributes.
I've got a select menu like this:
<select name="invoice_line[0][vat]" class="vat">
<option value="20440" data-value="21.00" data-name="20440" selected="selected">21%</option>
<option value="20441" data-value="6.00" data-name="20441">6%</option>
<option value="20442" data-value="0.00" data-name="20442">0%</option>
</select>
How can I get the values of the attributes 'data-value', 'data-name' and 'value' of the selected option?
obj = $("#dropdown").select2("data")
in obj variable i will get all the data of the selected node.
This was answered in another SO question
There is no direct method with select2, you can use a combinaison of select2 data and jQuery :
$("#example").select2().find(":selected").data("id");
First you get the select2 data then you find your selected option with jQuery and finally the data-attribute.
We can use a combination of select2 data and jQuery :
$("#example").select2('data').element[0].attributes['data-name'].value
Following worked for me. Idea is to use "change" function as follows
<select class="drop-down">
<option value="0">A</option>
<option value="1">B</option>
</select>
$('.drop-down').select2().on("change", function(e) {
var obj = $(".drop-down").select2("data");
console.log("change val=" + obj[0].id); // 0 or 1 on change
});
var return_option = $("#your-select-input-id").select2().find(":selected")[0];
above given statement will return select option and then put that return result as given below:
var name_of_attribute = $( return_option ).attr('name-of-attribute');
This will return the attribute value.
No idea about the pluggin, and without checking if the code works i imagine it would be something like this:
$('.vat li').each(function(){
var me = $(this),
mevalue = me.attr('value'),
datavalue = me.data('value'),
dataname = me.data('name');
//do what you want with the data?
});
Put select2 into tagging mode , it will help you.
Or
Try below similar code, it may work for you ...
$("$id").select2("val", option);
$("$id").attr("data-name");
I know that this is an old post, but I was struggling with this same problem. This is the solution that me and my good friend Thys finally got to work:
<script type="text/javascript">
$(document).ready(function ()
{
$("#e1").select2();
$("#e1").change(function () {
var theID = $("#e1").val();
$('#staffNr').val(theID);
$('#staffNr').val();
//var theID = $(test).select2('data').id;
var theSelection = $(test).select2('data').text;
$('#selectedID').text(theID);
$('#selectedText').text(theSelection);
});
});
#Html.Hidden("fieldName","staffNr");
This worked in my MVC 4 view with the last line in my html form where it is correctly added to the model. Don't forget to up-vote if you use my answer please :) I haven't got much of a reputation...
I hope you solved the issue. Here we dont use select2(), if we use select2() it will not work all other functions like formatNoMatches, on-change....
$("#example").find(":selected").data("id");
el = document.getElementsByName("invoice_line[0][vat]")
el.options[[el.selectedIndex]].attributes["data-id"].value
The params.data.element object of the selected item holds the data you're looking for.
Where .foo is the select element I'm calling, and the data attribute within the options I want to access is data-bar="some value" The following works for me:
var $fooSelect = $('.foo');
$fooSelect.on(function (e) {
console.log($(e.params.data.element).data('bar'));
});
You can access to attributes looking in DOM structure:
<select id="select_name">
<option value="20440" data-value="21.00">21%</option>
<option value="20441" data-value="6.00">6%</option>
<option value="20442" data-value="0.00">0%</option>
</select>
$('#select_name option').each(function (index) {
console.log($(this).attr("data-value"));
});
set an id for your select element and this would work
$('select#your-id').find('option[value="'+$('#your-id').val()+'"]').attr('data-attribute');
You haveto do it with on("change"... because of this is a dynamicly generated option list.
$('.select_class').on("change",function(){
var selected_value= $('.hakemler').val();
var wanted= $('.select_class').find('option[value="'+selected_value+'"]').attr('data-foo');
alert(selected_value+" "+wanted);
});

How to get the selected option in an html using jquery

I want to retrieve the id of my option that I selected. Over here you can see my HTML.
<select name="zaal" id="zaal">
<DIV CONTENTEDITABLE="FALSE" ID="MACONTAINER" MACONSTRAINT="" MAPARAMETER="ZALEN">
<DIV CONTENTEDITABLE="TRUE" ID="MAITEM">
<option value="~#ITEM.ID~" id="ZAALNAME">~ITEM.ID~, ~ITEM.NAME~</option>
</DIV>
</DIV>
</select>
I am doing it like this.
var selectVal = $("#zaal :selected").val();
var id = selectVal.substring(1);
console.log("id is: " + selectVal);
But for some reason it won't work.
Can anybody help?
EDIT
Ok the divs are the problem. But I need those to get my values from my database.So I think I need to find another solution than a select.
$("#zaal option:selected").attr('value'); // will return you ~#ITEM.ID~
To get the id
$("#zaal option:selected").attr('id'); // will return you ZAALNAME
To get id on selection change try this:
$('#zaal').on('change', function() {
// To get id
$('option:selected', this).attr('id');
$('option:selected', this).attr('value'); // return the value of selected option
// To get the select box value
var value = this.value;
});
Maybe try:
$("#zaal option:selected").val();
Also, try moving the divs outside of the select element.
Look at this question:
<div> and <select> tags
You can only put <option> or <optgroup> inside a <select>. If you want to put anything else in there you have to make some kind of list yourself.
Why would you like to put any div inside a select anyway?
If I put the HTML you gave me (with edited strings) inside Google Chome, this is what is made of your code:
<select name="zaal" id="zaal">
<option value="x" id="ZAALNAME">X, Y</option>
</select>
$("#zaal option[value='0']").text()
Try this:
var selectVal = $("#zaal option:selected").val();
var id = selectVal.substring(1);
console.log("id is: " + selectVal);
The html should be
<select name="zaal" id="zaal">
<option value="~#ITEM.ID~" id="ZAALNAME">~ITEM.ID~, ~ITEM.NAME~</option>
</select>
$('#zaal').change(function(){
alert($($(this)+':selected').attr('id'));
});
Fiddle http://jsfiddle.net/cBaZ7/1/
val() will retrieve the value of the selected option. It is not the id
So try this:
$("#zaal option:selected").attr("id")

Getting the text from a drop-down box

This gets the value of whatever is selected in my dropdown menu.
document.getElementById('newSkill').value
I cannot however find out what property to go after for the text that's currently displayed by the drop down menu. I tried "text" then looked at W3Schools but that didn't have the answer, does anybody here know?
For those not sure, here's the HTML for a drop down box.
<select name="newSkill" id="newSkill">
<option value="1">A skill</option>
<option value="2">Another skill</option>
<option value="3">Yet another skill</option>
</select>
Based on your example HTML code, here's one way to get the displayed text of the currently selected option:
var skillsSelect = document.getElementById("newSkill");
var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;
Simply You can use jQuery instead of JavaScript
$("#yourdropdownid option:selected").text();
Try This.
This should return the text value of the selected value
var vSkill = document.getElementById('newSkill');
var vSkillText = vSkill.options[vSkill.selectedIndex].innerHTML;
alert(vSkillText);
Props: #Tanerax for reading the question, knowing what was asked and answering it before others figured it out.
Edit: DownModed, cause I actually read a question fully, and answered it, sad world it is.
document.getElementById('newSkill').options[document.getElementById('newSkill').selectedIndex].value
Should work
This works i tried it my self i thought i post it here in case someone need it...
document.getElementById("newSkill").options[document.getElementById('newSkill').selectedIndex].text;
Attaches a change event to the select that gets the text for each selected option and writes them in the div.
You can use jQuery it very face and successful and easy to use
<select name="sweets" multiple="multiple">
<option>Chocolate</option>
<option>Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div></div>
$("select").change(function () {
var str = "";
$("select option:selected").each(function() {
str += $( this ).text() + " ";
});
$( "div" ).text( str );
}).change();
function getValue(obj)
{
// it will return the selected text
// obj variable will contain the object of check box
var text = obj.options[obj.selectedIndex].innerHTML ;
}
HTML Snippet
<asp:DropDownList ID="ddl" runat="server" CssClass="ComboXXX"
onchange="getValue(this)">
</asp:DropDownList>
Here is an easy and short method
document.getElementById('elementID').selectedOptions[0].innerHTML
Does this get the correct answer?
document.getElementById("newSkill").innerHTML
var ele = document.getElementById('newSkill')
ele.onchange = function(){
var length = ele.children.length
for(var i=0; i<length;i++){
if(ele.children[i].selected){alert(ele.children[i].text)};
}
}
var selectoption = document.getElementById("dropdown");
var optionText = selectoption.options[selectoption.selectedIndex].text;
Please try the below this is the easiest way and it works perfectly
var newSkill_Text = document.getElementById("newSkill")[document.getElementById("newSkill").selectedIndex];
Found this a tricky question but using ideas from here I eventually got the solution using PHP & Mysqli to populate the list : and then a bit of javascript to get the working variable out.
<select id="mfrbtn" onchange="changemfr()" >
<option selected="selected">Choose one</option>
<?php
foreach($rows as $row)
{
echo '<option value=implode($rows)>'.$row["Mfrname"].'</option>';
}
?>
</select>
Then :
<script language="JavaScript">
function changemfr()
{
var $mfr2=document.getElementById("mfrbtn").selectedOptions[0].text;
alert($mfr2);
}
</script>

Categories

Resources