How do I get selected value from Drop Down List? - javascript

I have a drop down list (DDL)...
I would usually just use $('#ddl option:selected').val()
but I have stored the jQuery object...
var myDDL = $('#ddl');
I can't figure out how I would use the variable myDDL alongside with option:selected
Not sure how to word my question really...

You simply need to call val() on the select object to get the selected value.
$('#ddl').val()
To get the variable just for the sake of knowing you can use find
selectedVal = myDDL.find('option:selected').val();
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of select elements, it
returns null when no option is selected and an array containing the
value of each selected option when there is at least one and it is
possible to select more because the multiple attribute is present, jQuery Docs

Please try this.
Call this below function to see the effects.
----------------------- JS-Code -----------------------
TestFunction();
function TestFunction() {
var myDDL = $('#ddl');
var selectedVal = myDDL.find('option:selected').val();
alert(selectedVal);
}
-------------------- HTML Code --------------------------
<div id="divTest">
<select id="ddl">
<option>one</option>
<option selected="selected">two</option>
</select>
</div>

HTML:
<select id="ddlCountry" name="ddlCountry">
<option selected="selected" value="1">India
</option>
<option value="2">USA
</option>
</select>
JQuery:
$('#ddlCountry').val()
I hope this helps. If this does resolve your problem, please mark the post as answered.
Thanks,
Prashant

Try with this:
myDDL.find('option:selected').val();
As myDDL is a jQuery object, so you can use .find() method to get the selected value.

Related

Can't change selected option in a select

I have a select and I want it's selected option to change but I can't make it happen for some reason. This is the code that I have.
$("#ID option[value=grpValue]").prop('selected', 'selected').change();
If instead of using "grpValue" I type in the value manually for example value "3" it does work. But I want it to use grpValue.
So this for example does work.
$("#ID option[value=3]").prop('selected', 'selected').change();
What am I doing wrong in the first line?
Would appreciate the help, thanks in advance.
EDIT: I've already tried using option[value='grpValue'], doesn't work.
$(document).ready(function(){
$("#sel option[value='c']").attr("selected",true);
$("#sel option[value='c']").prop("selected",true);
});
<html><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head>
<body>
<form>
<select id="sel">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</form>
</body>
</html>
you can use any one from prop() or attr() method both of useful
Is grpValue a variable? If so
$("#ID option[value="+grpValue+"]").prop('selected', 'selected').change();
will make the attribute selector do the work.
BTW, I think
$obj.prop('selected', true);
is the correct expression for prop.
$('#id_of_select').val('value_of_option_here');
Edit: To explain why the above code works. The first part:
Is the jQuery we use the following method to select an element by it's id, we could also select an element by it's class by simply changing the '#' to a '.'.
$('#id_of_select')
The statement following it refers to the value attribute that is attached to every input, select, textarea and button. The value is the string that is passed through when a form is submitted. For inputs this is the typed text, for selects it's the value of the selected option.
When we click an option in a select field, what we are actually doing is grabbing the value of the option and setting it as the selects value also, selects know what value is selected via the value, it can then grab the option text associated with this value. The code below (with a parameter) will set the value of the select field, in the same way it would if you were to click the option.
Note .val must have a parameter otherwise you are just asking jQuery what the value of the selected field is. With a value will set, without a value will get.
.val('value_of_option_here');
Hope this is a little more useful than my original answer, I've tried to break it down as much as possible though if it's a little confusing let me know.
Working example :
$("#ID option[value='b']").prop('selected', 'selected').change();
// if value in variable just replace $("#ID option[value="+valueInVar+"]")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ID" >
<option value = "a">a</option>
<option value = "b">b</option>
<option value = "c">c</option>
</select>

attr('selected','selected') not working in selectpicker bootsrap with ajax [duplicate]

I am attempting to retrieve and set the selected value of a select element (drop down list) with jQuery.
for retrievel i have tried $("#myId").find(':selected').val(), as well as $("#myId").val() but both return undefined.
Any insight into this problem would be much appreciated.
to get/set the actual selectedIndex property of the select element use:
$("#select-id").prop("selectedIndex");
$("#select-id").prop("selectedIndex",1);
The way you have it is correct at the moment. Either the id of the select is not what you say or you have some issues in the dom.
Check the Id of the element and also check your markup validates at here at W3c.
Without a valid dom jQuery cannot work correctly with the selectors.
If the id's are correct and your dom validates then the following applies:
To Read Select Option Value
$('#selectId').val();
To Set Select Option Value
$('#selectId').val('newValue');
To Read Selected Text
$('#selectId>option:selected').text();
$('#myId').val() should do it, failing that I would try:
$('#myId option:selected').val()
When setting with JQM, don't forget to update the UI:
$('#selectId').val('newValue').selectmenu('refresh', true);
$("#myId").val() should work if myid is the select element id!
This would set the selected item: $("#myId").val('VALUE');
Suppose you have created a Drop Down list using SELECT tag like as follows,
<select id="Country">
Now if you want to see what is the selected value from drop down using JQuery then, simply put following line to retrieve that value..
var result= $("#Country option:selected").text();
it will work fine.
I know this is old but I just had a bear of a time with Razor, could not get it to work no matter how hard I tried. Kept coming back as "undefined" no matter if I used "text" or "html" for attribute. Finally I added "data-value" attribute to the option and it read that just fine.
<option value="1" data-value="MyText">MyText</option>
var DisplayText = $(this).find("option:selected").attr("data-value");
$( "#myId option:selected" ).text(); will give you the text that you selected in the drop down element. either way you can change it to .val(); to get the value of it . check the below coding
<select id="myId">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>`
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
Try this
$('#your_select_element_id').val('your_value').attr().add('selected');

jQuery find not working for select="selected"

How do I get all selected options from a <select> using jQuery?
<select id="mySelector" ... >
<option value="1" selected="selected">option1</option>
<option value="2" selected="selected">option2</option>
<option value="3">option3</option>
</select>
I tried $('#mySelector').find(":selected"). It returns [].
But if my options have only selected property instead of selected="selected" $('#mySelector').find(":selected") returns the correct results.
Am I doing something wrong?
There is little difference between attributes and properties.
Attributes does have assigned values like attr="value".
While properties are just a property which does not have any value assigned like checked, selected etc..
so to answer your question i would say then you have to use .map() iterations to create array:
var arr = $('#mySelector option').map(function(){
return $(this).attr('selected') === "selected"
}).get();
You can try both, one after another:
$('#mySelector').find(":selected")//animate...
$('#mySelector').each(function(){
if ($(this).attr('selected') === "selected"){
//animate...
}
}
Setting the attribute selected="selected" will work as a pre-selected option and will be displayed first in the drop-down list.
However, I guess the user chooses something and you want to get that value.
$('select option:selected').each(function () {
alert($(this).val());
});
Iterate through each one in the select element and with the pseudo selector :selected just get it's value.
JsFiddle demo
Note: If you instead want the text, not the value, use .text() instead of .val()

multiple select element - onchange

I have a select element that allows for multiple selections. I'd like to display the selected values in another part of the page (in a div or something) as the user makes changes to what is selected.
Is the only way of doing this to iterate over the "options" and check if "selected" is true? this would not be preferable since each "onchange" event would require the entire select element to be iterated over.
Here's a fiddle that demonstrates how I am currently doing it, but I'm hoping maybe there's a better way than having to iterate over all the options on every "change": multiple select elment onchange fiddle
.val() on a multiple select returns an array.
See the snippet below as an example:
$(function() {
$('#fruits').change(function(e) {
var selected = $(e.target).val();
console.dir(selected);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="true" id="fruits">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="mango">Mango</option>
<option value="grape">Grape</option>
<option value="watermelon">watermelon</option>
</select>
In your fiddle, I just used .val(). This returns an array
JSFiddle Link
$(function() {
$('#fruits').change(function() {
console.log($(this).val());
});
});
If you could use jQuery it might be as easy as:
$('select').change(function() {alert($(this).val())})
You could use blur instead of change, so that the select is only processed once, rather than on each selection. http://jsfiddle.net/2mSUS/3/
$(function() {
$('#fruits').change(function(e) {
var selected = $(e.target).val();
console.dir(selected);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="true" id="fruits">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="mango">Mango</option>
<option value="grape">Grape</option>
<option value="watermelon">watermelon</option>
</select>
You can use the :selected Selector of jQuery instead, but I believe that under the hood, jQuery does a loop on the selected = true.
element.addEventListener('click', function(){alert(this.value)})
This is a solution in JS, you can port it over to jQuery pretty easily. The idea is to add a click listener to each option in the selection. This will not work in IE8 and below because of addEventListener, there are ways to get around this though.
I think this is a better approach then having to reiterate over the list. You will have to have a listener attached to each option though.
This works:
var MyControl = document.getElementById('Control_ID');
var newValue = MyControl[MyControl.selectedIndex].value;
Of course, Control_ID is the ID of the select control.
I'm doing a form submit. My template helper looks like this:
'submit #update': function(event) {
event.preventDefault();
var obj_opts = event.target.tags.selectedOptions; //returns HTMLCollection
var array_opts = Object.values(obj_opts); //convert to array
var stray = array_opts.map((o)=> o.text ); //to filter by: text, value or selected
//stray is now ["Test", "Milk Free"] for example, depending on the selection
//...do stuff...
}
You could use a similar pattern for 'onchange'

How pass selected index value to a change function

I have a select menu that looks like this:
<select id ="cal-category-select">
<option value="/event-sort/list/2009/9/sports/">Sports Events</option>
<option value="/event-sort/list/2009/9/fine-arts/">Fine Arts Events</option>
...
</select>
When the user selects an option from the select, I need to pass the option value attribute to this function as event data, it's the second parameter:
$('#cal-category-select').bind('change.filter', need_value_attribute_here, update_cal);
The update_cal function referenced receives the data passed in from the second parameter and using to get some ajax content.
Any idea how I can do that? I haven't been able to get it to work.
I have tried this:
var category_url = $('#cal-category-select option:selected').attr('value');
$('#cal-category-select').unbind().bind('change.filter', category_url, update_cal);
but that only returns the first option value in the list.
You would just use:
$("#cal-category-select").val()
alternative longer syntax:
$('#cal-category-select option:selected').val()
$('#cal-category-select').bind('change.filter', function(){
update_cal($(this).val());
});
For the selected <option> value, it should just be
$('#cal-category-select').val();

Categories