If you know the Index, Value or Text. also if you don't have an ID for a direct reference.
This, this and this are all helpful answers.
Example markup
<div class="selDiv">
<select class="opts">
<option selected value="DEFAULT">Default</option>
<option value="SEL1">Selection 1</option>
<option value="SEL2">Selection 2</option>
</select>
</div>
A selector to get the middle option-element by value is
$('.selDiv option[value="SEL1"]')
For an index:
$('.selDiv option:eq(1)')
For a known text:
$('.selDiv option:contains("Selection 1")')
EDIT: As commented above the OP might have been after changing the selected item of the dropdown. In version 1.6 and higher the prop() method is recommended:
$('.selDiv option:eq(1)').prop('selected', true)
In older versions:
$('.selDiv option:eq(1)').attr('selected', 'selected')
EDIT2: after Ryan's comment. A match on "Selection 10" might be unwanted. I found no selector to match the full text, but a filter works:
$('.selDiv option')
.filter(function(i, e) { return $(e).text() == "Selection 1"})
EDIT3: Use caution with $(e).text() as it can contain a newline making the comparison fail. This happens when the options are implicitly closed (no </option> tag):
<select ...>
<option value="1">Selection 1
<option value="2">Selection 2
:
</select>
If you simply use e.text any extra whitespace like the trailing newline will be removed, making the comparison more robust.
None of the methods above provided the solution I needed so I figured I would provide what worked for me.
$('#element option[value="no"]').attr("selected", "selected");
You can just use val() method:
$('select').val('the_value');
By value, what worked for me with jQuery 1.7 was the below code, try this:
$('#id option[value=theOptionValue]').prop('selected', 'selected').change();
There are a number of ways to do this, but the cleanest approach has been lost among the top answers and loads of arguments over val(). Also some methods changed as of jQuery 1.6, so this needs an update.
For the following examples I will assume the variable $select is a jQuery object pointing at the desired <select> tag, e.g. via the following:
var $select = $('.selDiv .opts');
Note 1 - use val() for value matches:
For value matching, using val() is far simpler than using an attribute selector: https://jsfiddle.net/yz7tu49b/6/
$select.val("SEL2");
The setter version of .val() is implemented on select tags by setting the selected property of a matching option with the same value, so works just fine on all modern browsers.
Note 2 - use prop('selected', true):
If you want to set the selected state of an option directly, you can use prop (not attr) with a boolean parameter (rather than the text value selected):
e.g. https://jsfiddle.net/yz7tu49b/
$option.prop('selected', true); // Will add selected="selected" to the tag
Note 3 - allow for unknown values:
If you use val() to select an <option>, but the val is not matched (might happen depending on the source of the values), then "nothing" is selected and $select.val() will return null.
So, for the example shown, and for the sake of robustness, you could use something like this https://jsfiddle.net/1250Ldqn/:
var $select = $('.selDiv .opts');
$select.val("SEL2");
if ($select.val() == null) {
$select.val("DEFAULT");
}
Note 4 - exact text match:
If you want to match by exact text, you can use a filter with function. e.g. https://jsfiddle.net/yz7tu49b/2/:
var $select = $('.selDiv .opts');
$select.children().filter(function(){
return this.text == "Selection 2";
}).prop('selected', true);
although if you may have extra whitespace you may want to add a trim to the check as in
return $.trim(this.text) == "some value to match";
Note 5 - match by index
If you want to match by index just index the children of the select e.g. https://jsfiddle.net/yz7tu49b/3/
var $select = $('.selDiv .opts');
var index = 2;
$select.children()[index].selected = true;
Although I tend to avoid direct DOM properties in favour of jQuery nowadays, to future-proof code, so that could also be done as https://jsfiddle.net/yz7tu49b/5/:
var $select = $('.selDiv .opts');
var index = 2;
$select.children().eq(index).prop('selected', true);
Note 6 - use change() to fire the new selection
In all the above cases, the change event does not fire. This is by design so that you do not wind up with recursive change events.
To generate the change event, if required, just add a call to .change() to the jQuery select object. e.g. the very first simplest example becomes https://jsfiddle.net/yz7tu49b/7/
var $select = $('.selDiv .opts');
$select.val("SEL2").change();
There are also plenty of other ways to find the elements using attribute selectors, like [value="SEL2"], but you have to remember attribute selectors are relatively slow compared to all these other options.
Using jquery-2.1.4, I found the following answer to work for me:
$('#MySelectionBox').val(123).change();
If you have a string value try the following:
$('#MySelectionBox').val("extra thing").change();
Other examples did not work for me so that's why I'm adding this answer.
I found the original answer at:
https://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu
Exactly it will work try this below methods
For normal select option
<script>
$(document).ready(function() {
$("#id").val('select value here');
});
</script>
For select 2 option trigger option need to use
<script>
$(document).ready(function() {
$("#id").val('select value here').trigger('change');
});
</script>
$(elem).find('option[value="' + value + '"]').attr("selected", "selected");
You could name the select and use this:
$("select[name='theNameYouChose']").find("option[value='theValueYouWantSelected']").attr("selected",true);
It should select the option you want.
Answering my own question for documentation. I'm sure there are other ways to accomplish this, but this works and this code is tested.
<html>
<head>
<script language="Javascript" src="javascript/jquery-1.2.6.min.js"></script>
<script type="text/JavaScript">
$(function() {
$(".update").bind("click", // bind the click event to a div
function() {
var selectOption = $('.selDiv').children('.opts') ;
var _this = $(this).next().children(".opts") ;
$(selectOption).find("option[index='0']").attr("selected","selected");
// $(selectOption).find("option[value='DEFAULT']").attr("selected","selected");
// $(selectOption).find("option[text='Default']").attr("selected","selected");
// $(_this).find("option[value='DEFAULT']").attr("selected","selected");
// $(_this).find("option[text='Default']").attr("selected","selected");
// $(_this).find("option[index='0']").attr("selected","selected");
}); // END Bind
}); // End eventlistener
</script>
</head>
<body>
<div class="update" style="height:50px; color:blue; cursor:pointer;">Update</div>
<div class="selDiv">
<select class="opts">
<option selected value="DEFAULT">Default</option>
<option value="SEL1">Selection 1</option>
<option value="SEL2">Selection 2</option>
</select>
</div>
</body>
</html>
For setting select value with triggering selected:
$('select.opts').val('SEL1').change();
For setting option from a scope:
$('.selDiv option[value="SEL1"]')
.attr('selected', 'selected')
.change();
This code use selector to find out the select object with condition, then change the selected attribute by attr().
Futher, I recommend to add change() event after setting attribute to selected, by doing this the code will close to changing select by user.
$('#select option[data-id-estado="3"]').prop("selected",true).trigger("change");
// or
$('#select option[value="myValue"]').prop("selected",true).trigger("change");
Try this
you just use select field id instead of #id (ie.#select_name)
instead of option value use your select option value
<script>
$(document).ready(function() {
$("#id option[value='option value']").attr('selected',true);
});
</script>
I use this, when i know the index of the list.
$("#yourlist :nth(1)").prop("selected","selected").change();
This allows the list to change, and fire the change event.
The ":nth(n)" is counting from index 0
i'll go with:-
$("select#my-select option") .each(function() { this.selected = (this.text == myVal); });
/* This will reset your select box with "-- Please Select --" */
<script>
$(document).ready(function() {
$("#gate option[value='']").prop('selected', true);
});
</script>
For Jquery chosen if you send the attribute to function and need to update-select option
$('#yourElement option[value="'+yourValue+'"]').attr('selected', 'selected');
$('#editLocationCity').chosen().change();
$('#editLocationCity').trigger('liszt:updated');
if you want to not use jQuery, you can use below code:
document.getElementById("mySelect").selectedIndex = "2";
The $('select').val('the_value'); looks the right solution and if you have data table rows then:
$row.find('#component').val('All');
Thanks for the question. Hope this piece of code will work for you.
var val = $("select.opts:visible option:selected ").val();
There are a few suggestions why you should use prop instead of attr. Definitely use prop as I've tested both and attr will give you weird results except for the simplest of cases.
I wanted a solution where selecting from an arbitrarily grouped select options automatically selected another select input on that same page. So for instance, if you have 2 dropdowns - one for countries, and the other for continents. In this scenario, selecting any country automatically selected that country's continent on the other continent dropdown.
$("#country").on("change", function() {
//get continent
var originLocationRegion = $(this).find(":selected").data("origin-region");
//select continent correctly with prop
$('#continent option[value="' + originLocationRegion + '"]').prop('selected', true);
});
$("#country2").on("change", function() {
//get continent
var originLocationRegion = $(this).find(":selected").data("origin-region");
//select continent wrongly with attr
$('#continent2 option[value="' + originLocationRegion + '"]').attr('selected', true);
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<form>
<h4 class="text-success">Props to the good stuff ;) </h4>
<div class="form-row">
<div class="form-group col-md-6 col-sm-6">
<label>Conuntries</label>
<select class="custom-select country" id="country">
<option disabled selected>Select Country </option>
<option data-origin-region="Asia" value="Afghanistan">Afghanistan</option>
<option data-origin-region="Antartica" value="Antartica">Antartica</option>
<option data-origin-region="Australia" value="Australia">Australia</option>
<option data-origin-region="Europe" value="Austria">Austria</option>
<option data-origin-region="Asia" value="Bangladesh">Bangladesh</option>
<option data-origin-region="South America" value="Brazil">Brazil</option>
<option data-origin-region="Africa" value="Cameroon">Cameroon</option>
<option data-origin-region="North America" value="Canada">Canada</option>
<option data-origin-region="South America" value="Chile">Chile</option>
<option data-origin-region="Asia" value="China">China</option>
<option data-origin-region="South America" value="Ecuador">Ecuador</option>
<option data-origin-region="Australia" value="Fiji">Fiji</option>
<option data-origin-region="North America" value="Mexico">Mexico</option>
<option data-origin-region="Australia" value="New Zealand">New Zealand</option>
<option data-origin-region="Africa" value="Nigeria">Nigeria</option>
<option data-origin-region="Europe" value="Portugal">Portugal</option>
<option data-origin-region="Africa" value="Seychelles">Seychelles</option>
<option data-origin-region="North America" value="United States">United States</option>
<option data-origin-region="Europe" value="United Kingdom">United Kingdom</option>
</select>
</div>
<div class="form-group col-md-6 col-sm-6">
<label>Continent</label>
<select class="custom-select" id="continent">
<option disabled selected>Select Continent</option>
<option disabled value="Africa">Africa</option>
<option disabled value="Antartica">Antartica</option>
<option disabled value="Asia">Asia</option>
<option disabled value="Europe">Europe</option>
<option disabled value="North America">North America</option>
<option disabled value="Australia">Australia</option>
<option disabled value="South America">South America</option>
</select>
</div>
</div>
</form>
<hr>
<form>
<h4 class="text-danger"> Attributing the bad stuff to attr </h4>
<div class="form-row">
<div class="form-group col-md-6 col-sm-6">
<label>Conuntries</label>
<select class="custom-select country-2" id="country2">
<option disabled selected>Select Country </option>
<option data-origin-region="Asia" value="Afghanistan">Afghanistan</option>
<option data-origin-region="Antartica" value="Antartica">Antartica</option>
<option data-origin-region="Australia" value="Australia">Australia</option>
<option data-origin-region="Europe" value="Austria">Austria</option>
<option data-origin-region="Asia" value="Bangladesh">Bangladesh</option>
<option data-origin-region="South America" value="Brazil">Brazil</option>
<option data-origin-region="Africa" value="Cameroon">Cameroon</option>
<option data-origin-region="North America" value="Canada">Canada</option>
<option data-origin-region="South America" value="Chile">Chile</option>
<option data-origin-region="Asia" value="China">China</option>
<option data-origin-region="South America" value="Ecuador">Ecuador</option>
<option data-origin-region="Australia" value="Fiji">Fiji</option>
<option data-origin-region="North America" value="Mexico">Mexico</option>
<option data-origin-region="Australia" value="New Zealand">New Zealand</option>
<option data-origin-region="Africa" value="Nigeria">Nigeria</option>
<option data-origin-region="Europe" value="Portugal">Portugal</option>
<option data-origin-region="Africa" value="Seychelles">Seychelles</option>
<option data-origin-region="North America" value="United States">United States</option>
<option data-origin-region="Europe" value="United Kingdom">United Kingdom</option>
</select>
</div>
<div class="form-group col-md-6 col-sm-6">
<label>Continent</label>
<select class="custom-select" id="continent2">
<option disabled selected>Select Continent</option>
<option disabled value="Africa">Africa</option>
<option disabled value="Antartica">Antartica</option>
<option disabled value="Asia">Asia</option>
<option disabled value="Europe">Europe</option>
<option disabled value="North America">North America</option>
<option disabled value="Australia">Australia</option>
<option disabled value="South America">South America</option>
</select>
</div>
</div>
</form>
</div>
As seen in the code snippet, prop works correctly every time, but attr fails to select properly once the option has been selected once.
Keypoint: We're usually interested in the property of the attribute, so its safer to use prop over attr in most situations.
Related
I have a multiple select like this one could be:
<select multiple id="brand">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
And I'm looking for a way to end up like:
<select multiple id="brand">
<option value="volvo" selected="selected">Volvo</option>
<option value="saab" selected="selected">Saab</option>
<option value="opel" selected="selected">Opel</option>
<option value="audi" selected="selected">Audi</option>
</select>
I can't depend on external libraries and I can't make the .each function to work properly.
Besides I'm getting the original dinamically set with many fields, and this will be set to this only in a particular case, but i can't figure out why this isn't working for me.
The closest approach i found is:
$("#brand").each(function(){$(this).attr("selected","selected");});
Can you please point me out where I'm going wrong? Thanks
You need to select the options, for instance with a #brand > option selector:
$("#brand > option").each(function() {
$(this).attr("selected","selected");
});
console.log($("#brand").html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple id="brand">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
in Vanilla Script you could use something like this
document.querySelectorAll('#brand option').forEach((o)=>{
o.selected = 'selected'
})
If You need IE, be aware that for Each is not supported with node Lists. This should work inkl. IE
nodesArray = [].slice.call(document.querySelectorAll("#brand option"));
nodesArray.forEach(function (o) {
o.selected = 'selected'
})
You wont see the changes in HTML Code, but the DOM Properties of the options will change. Hope this helps.
I`ve a "select":
<select class="date-select2" name="date">
<option selected="selected" value="">All</option>
<option value="11-2015">11-2015</option>
<option value="10-2015">10-2015</option>
<option value="09-2015">09-2015</option>
<option value="07-2015">07-2015</option>
<option value="06-2015">06-2015</option>
<option value="04-2015">04-2015</option>
<option value="03-2015">03-2015</option>
</select>
When I`m try to get value of select,
document.getElementsByClassName('date-select2')[0].value
it normally returns a value of selected item in Chrome. In FF and Safari sometimes it returns an empty string, when selected a numeric value(not "All").
How to deal with it?
I think this might help you:
HTML
<select class="date-select2" name="date" onchange="myFunction(this.value)">
<option selected="selected" value="">All</option>
<option value="11-2015">11-2015</option>
<option value="10-2015">10-2015</option>
<option value="09-2015">09-2015</option>
<option value="07-2015">07-2015</option>
<option value="06-2015">06-2015</option>
<option value="04-2015">04-2015</option>
<option value="03-2015">03-2015</option>
</select>
JavaScript
function myFunction(curValue) {
alert(curValue);
}
Working : Fiddle
Note: Also remember to put your JavaScript code inside body also right before it ends.
var select = document.querySelector('select.date-select2');
// add onchange handler
select.onchange = function(){
var idx = select.selectedIndex;
var val = select.options[idx].value;
// if All is selected use text of option
if(val=="")
val = select.options[idx].textContent;
};
You can try this way to get selected item:
$(".date-select2 option:selected").text();
Please, explain how can I change 'selected' property of option?
E.g.:
<select id="lang_select">
<option value="en" selected="selected">english</option>
<option value="ar">العربية</option>
<option value="az">azərbaycanlı</option>
<option value="bg">български</option>
<option value="ca">català</option>
<option value="cs">český</option>
<!-- some data cut -->
</select>
So, if I change the drop down list value nothing is changed in html-data.
Why?
Only if I try to force reload the property using jQuery it works.
$(document).on('change',"select",function(){
var i = $(this)[0].selectedIndex;
var ch = $(this).children().each(function(index){
$(this).prop('selected',index == i);
if (index == i) {
$(this).attr('selected','selected');
} else {
$(this).removeAttr('selected');
}
});
});
Why? How can I avoid this? Is it possible to change "selected" using pure html?
EDIT
I namely want this attrbute in html tag because I need to save and restore the part of this html-code in future.
Updated, substituted .attr("selected", true) for .prop("selected", true)
Note , value of selected attribute returns true or false , not "selected".
Try utilizing selector $("option[value=" + this.value + "]", this) , set property selected to true , .siblings() to remove selected attribute from option not selected
$(document).on("change","select",function(){
$("option[value=" + this.value + "]", this)
.attr("selected", true).siblings()
.removeAttr("selected")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="lang_select">
<option value="en" selected="true">english</option>
<option value="ar">العربية</option>
<option value="az">azərbaycanlı</option>
<option value="bg">български</option>
<option value="ca">català</option>
<option value="cs">český</option>
<!-- some data cut -->
</select>
It's not change the html itself but it does change the value of the select
$('select').change(function(){
$('#result').html($(this).val());
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="lang_select">
<option value="en" selected="selected">english</option>
<option value="ar">العربية</option>
<option value="az">azərbaycanlı</option>
<option value="bg">български</option>
<option value="ca">català</option>
<option value="cs">český</option>
<!-- some data cut -->
</select>
<hr />
<div id="result"></div>
Use the val() method. So in your case, $("#lang_select").val('en'); selects the english option. And by the way if you want the first option to be selected you don't need the selected="selected". By default the first option is automatically selected.
I want to build a drop down menu that the second selection will be displayed if the first selection data belongs to a specific category.
As you can see below, the first selection will be about COUNTRIES. If the country selected has states, then a second drop down selection will be displayed, containing the states of that country.
1)Is there a tag (in my code "xyz") that i can use it to separate the countries in "state" and "no-state" categories? If there is, how can i read the value of the "xyz" tag?
2) If i use the:
<option class="no-state" value="Germany">Germany</option>
and then use the jQuery to read it it will give me the value GermanySpain (which is correct but not what i want)
$('.no-state').val();
HTML PART
<div id="country">
<select>
<option xyz="no-state" value="Germany">Germany</option>
<option xyz="state" value="USA">USA</option>
<option xyz="no-state" value="Spain">Spain</option>
</select>
</div>
<div id="state" style="display:none" >
<select>
<option value="Utah">Utah</option>
<option value="New York">New York</option>
<option value="California">California</option>
</select>
</div>
JQUERY PART
$(document).ready(function(){
$('#country').change(function() {
if (the value of "xyz" tag is === 'no-state')
{
$('div#state').hide();
}
else
{
$('div#state').show();
}
});
});
What can i do to address this issue?
Thanks.
Added a variable to keep if a country has states or not according your custom attribute xyz
js
$(document).ready(function(){
$('#country').change(function() {
var hasStates = $(this).find("option:selected").attr("xyz");
if (hasStates == 'no-state')
{
$('div#state').hide();
}
else
{
$('div#state').show();
}
});
});
fiddle
I think you can make use of .data() jQuery method, which reads the data-* a valid html5 attribute, but you have to change your markup to fix and use this script:
$('#country select').change(function() {
if ($(this).find('option:selected').data('xyz') === 'no-state') {
$('div#state').hide();
} else {
$('div#state').show();
}
});
You have to add a data-* prefix to get to it and make it a valid html5 attribute.
<select>
<option data-xyz="no-state" value="Germany">Germany</option>
<option data-xyz="state" value="USA">USA</option>
<option data-xyz="no-state" value="Spain">Spain</option>
</select>
Using the class attribute isn't that bad:
HTML
<select>
<option class="no-state" value="Germany">Germany</option>
<option class="state" value="USA">USA</option>
<option class="no-state" value="Spain">Spain</option>
</select>
JavaScript
$(document).ready(function(){
$('#country').change(function() {
var $sel = $(this).find("option:selected");
if ($sel.hasClass("no-state"))
{
$('div#state').hide();
}
else
{
$('div#state').show();
}
});
});
Fiddle
First of all I would change your html structure to:
<select id="country">
<option xyz="no-state" value="Germany">Germany</option>
<option xyz="state" value="USA">USA</option>
<option xyz="no-state" value="Spain">Spain</option>
</select>
<select id="state" style="display: none;">
<option value="Utah">Utah</option>
<option value="New York">New York</option>
<option value="California">California</option>
</select>
Then you can simply do:
$("#country").change(function() {
var hasState = $(this).find(':selected').attr('xyz') === "state";
$("#state").toggle(hasState);
});
Here is a fiddle to see it in action.
I have two dropdown i want when i select for example from dropdown test1 option with value a
the second dropdown test2 show only the options that have value a
<select name="test1" id="test1" onchange="document.getElementById('test2').value=this.value">
<option value="Select">Select</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<select id="test2" name="test2">
<option value="Select">Select</option>
<option value="a">a</option>
<option value="a">b</option>
<option value="a">c</option>
<option value="b">1</option>
<option value="b">2</option>
<option value="b">3</option>
<option value="c">c</option>
</select>
Or you can go this way:
jQuery(document).ready(function($){
var options = $('#test2 option');
$('#test1').on('change', function(e){
$('#test2').append(options);
$('#test2 option[value!=' + $(this).val() +']').remove();
});
});
fiddle
Since you've tagged this with JQuery, if I were to not alter your HTML at all, you could do this by changing the JS in your onchange from this:
document.getElementById('test2').value=this.value
. . . to this:
$("test2").find("option").hide();
$("test2").find("[value^='" + $("test1").val() + "']").show();
That would hid all of the options in the "test2" dropdown, and then show all of the ones that have a value that starts with the value of the currently selected "test1" option.
Note: this will also work if you chose to update the code to only use the "test1" values as a prefix for the "test2" values. ;)
UPDATE: Fixed a typo in the code.
Like it was said, you really don't want to do it this way as each option should have a unique value....but here is one way to accomplish it: jsFiddle
Using jQuery, you could check for the value of the selected option in test1, hide all those in test2 that don't match then show those with a matching value.
$('#test1').on('change', function() {
$('#test2 option:not(option[value='+$(this).val()+'])').hide();
$('#test2 option[value='+$(this).val()+']').show();
});