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);
});
Related
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>
I have a select list that's generated by the Javascript code of my app
<select name="addToContexts" id="addToContexts">
<option selected>private</option>
<option>public</option>
<option>shared</option>
</select>
What I need to do is that when the user performs a certain action the selected parameter shifts to another option, so that the result would be something like:
<select name="addToContexts" id="addToContexts">
<option>private</option>
<option selected>public</option>
<option>shared</option>
</select>
Do you know if there's a way to do it without regenerating the whole options list simply using jQuery to get the select element by ID and to change the selected option?
Thank you!
<body>
<select name="addToContexts" id="addToContexts">
<option selected>private</option>
<option>public</option>
<option>shared</option>
</select>
<button id="changeSelect">Change</button>
<script>
$("#changeSelect").click(function(){
$("#addToContexts option:nth-child(2)").prop("selected", true);
});
</script>
</body>
Something like this?
Hope this help.
http://jsfiddle.net/6Ljn1rzr/
$('input[type=checkbox]').on(
'change',
function() {
$('option').attr("selected",false);
$('option:contains(public)').attr("selected",true);
}
);
its very simple you can visit this thread
http://www.stackoverflow.com/questions/1314245/set-the-selected-index-of-a-dropdown-using-jquery
it has explained the in a very good manner and hopefully you will get your answer from this thread
http://jsfiddle.net/washington_guedes/ovpkLexj/5/
I used an ul-li "click" event as "certain action"... and it worked well
$("li").on("click", function(){
var aux = $(this/*li*/).html();
$('#addToContexts > option')
.prop("selected", false)
.each(function(){
if( $(this/*option*/).html() === aux){
$(this/*option*/).prop("selected", true);
}
});
});
sorry guys, previously I didn't mention the my dropdown list is made with bootstrap. based on #rps suggestion I asked to my colleague(who is made template) he said it's made with bootstrap.
I am putting basic html dropdown code,so I think you guys can understand How bootstrap code will be.
html code:
<select name="primary" class="select-block" id="select_alert">
<option "selected">Choose Alert T</option>
<option value="T1">T1</option>
<option value="T2">T2</option>
<option value="T3">T3</option>
<option value="T4">T4</option>
</select>
Initially i am getting the select menu in the following way.
for my conformation,I am finding the menu value in the following way.
i/p: document.getElementById('select_alert').value
o/p: "choose Alert T"
Now using javascript or jquery, I want to change select option in the follwoing way.For this I tried the below it's not working
document.getElementById('select_alert').value="T1";
Again If I check the value of select menu,it should be "T1".
Thanks
you can try this
// Get the value from a dropdown select
$( "#select_alert option:selected").val();
$( "#select_alert option:selected" ).text();
My reading of the question is ambiguous, but if you're trying to set the value, or set the selected-option, to T1:
$('#select_alert option[value="T1"]').prop('selected',true);
JS Fiddle demo.
If you're trying to retrieve the value of the selected option:
$('#select_alert option:selected').val();
Using jQuery you can just do this:
$('#select_alert').val('T1');
Demo : Fiddle
use as follows :
$('#select_alert').val('T1'); // in jquery
also your javascript code is correct, there must be some other error on the page.
without jquery you can use
document.getElementById('select_alert').selectedIndex = 1
http://jsfiddle.net/uzqZA/1/
if you want to find out the option index by given value try this
var sel = document.getElementById('select_alert'),
selopt = sel.options,
searchidx;
//alert(selopt[sel.selectedIndex].value);
//sel.selectedIndex = 1;
//alert(selopt[sel.selectedIndex].value);
//alert(sel.value)
// search for the index
searchidx = getoptidx(selopt, "T3");
if (searchidx !== false) {
sel.selectedIndex = searchidx;
alert(selopt[sel.selectedIndex].value);
} else {
alert("index not found")
}
/**
* returns the index of a value
* #todo optimize search?
*/
function getoptidx(opts, searchterm) {
for (var i in opts) {
if (opts[i].text === searchterm) return i;
}
return false;
}
the fiddle: http://jsfiddle.net/uzqZA/6/
Try to do it this way :
$('#select_alert').val("T3");
$("#select_alert").selectmenu();
$("#select_alert").selectmenu("refresh");
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")
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>