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()
Related
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>
How do I get all select elements that do not have an option selected using jQuery?
<select id="one">
<option value=""></option>
<option value="test"></option>
</select>
<select id="two">
<option value=""></option>
<option selected value="test"></option>
</select>
What would the jQuery selector be that would return just #one based on no selection?
Refer to https://stackoverflow.com/a/63588880/3499595 if your case is not similar to OP (default value is "")
$('select option:selected[value=""]').parent()
Selects all the :selected options of all the select elements
Checks if the selected option has a value of "", which in your case means no option is actually selected.
Returns the parent (which would be a select)
You can take advantage of jQuery's .parent() and .not() functions. See below:
// selector for all 'select' elements with any option below it
var all = $("select>option").parent(); // alternative $("select")
// selector for all 'select' element with a selected child
var selected = $("select>option[selected]").parent();
// the subtraction set "all - selected" achieved by `not`.
var unselected = all.not(selected);
Note that jQuery's parent takes care of removing duplicates from a set of parents of child elements.
JsFiddle here.
The accepted answer gives all select elements with a selected option whose value is empty(""), which does answer the question in regard to the OP's sample HTML, where options with empty values are given, but it doesn't really answer the title question.
There is a difference between selecting an option with an empty value, and not selecting any option at all.
To select all select elements with no option selected, use
$('select').not(':has(option:selected)')
If you have jquery library then try
$('select option').filter(function(i,d){return !d.hasAttribute("selected")});
I needed help regarding selection copying, as I know nothing about it. Here's my problem: I need to select a state from one select, and then have it automatically select the same state in another select. But my values are different for each select, as the info will be processed to the server (otherwise, there wouldn't be a problem, because I wouldn't need to copy from one select to the other). Here is my format:
<select name="state" size="1" id="stateSelect">
<option value="AL">Alabama</option>
<select>
<select name="state" size="1" id="stateSelect2">
<option class="AL" value="Alabama">Alabama</option>
</select>
And this is my current jQuery that I've pieced together from all over the internet (that obviously doesn't work):
$(function(){
$("select[name*='state']").change(function(){
$("#stateSelect2").children(':selected').hasClass( $("#stateSelect").val() )
})
})
So, what I need is to be able to do is copy the value selected by "stateSelect", and select the value of "stateSelect2" by the class that has the value of the selected option of "stateSelect". I don't know how easy or hard this is to do, but I sure would appreciate any and all help with this issue. if you use JSFiddle, bonus points to you. Thanks!
$('#stateSelect').on('change', function(){
var v = $(this).val();
$('#stateSelect2 .'+v).prop('selected', true);
});
http://jsfiddle.net/dipser/9ca0eL1d/
Something like this should suffice:
$(document).ready(function(){
$('#stateSelect').on('change', function(){
var val = $(this).val();
if(val.length > 0 && $('#stateSelect2 option.' + val).length > 0) {
$('#stateSelect2 option.' + val).attr('selected', 'selected');
// could also use .prop() here instead of attr
// which would be .prop('selected', true);
}
});
});
The if statement makes sure that the selected option has a value and also exists in the second select.
JSFiddle Demo
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.
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'