I have a select
field with some options in it. Now I need to select one of those options
with jQuery. But how can I do that when I only know the value
of the option
that must be selected?
I have the following HTML:
<div class="id_100">
<select>
<option value="val1">Val 1</option>
<option value="val2">Val 2</option>
<option value="val3">Val 3</option>
</select>
</div>
I need to select the option with value val2
. How can this be done?
Here's a demo page: http://jsfiddle.net/9Stxb/
This question is related to
jquery
jquery-selectors
html-select
var opt = new Option(name, id);
$("#selectboxName").append(opt);
opt.setAttribute("selected","selected");
Use:
$("div.id_100 > select > option[value=" + value + "]").attr("selected",true);
This works for me. I'm using this code for parsing a value in a fancybox update form, and my full source from app.js is:
jQuery(".fancybox-btn-upd").click(function(){
var ebid = jQuery(this).val();
jQuery.ajax({
type: "POST",
url: js_base_url+"manajemen_cms/get_ebook_data",
data: {ebookid:ebid},
success: function(transport){
var re = jQuery.parseJSON(transport);
jQuery("#upd-kategori option[value="+re['kategori']+"]").attr('selected',true);
document.getElementById("upd-nama").setAttribute('value',re['judul']);
document.getElementById("upd-penerbit").setAttribute('value',re['penerbit']);
document.getElementById("upd-tahun").setAttribute('value',re['terbit']);
document.getElementById("upd-halaman").setAttribute('value',re['halaman']);
document.getElementById("upd-bahasa").setAttribute('value',re['bahasa']);
var content = jQuery("#fancybox-form-upd").html();
jQuery.fancybox({
type: 'ajax',
prevEffect: 'none',
nextEffect: 'none',
closeBtn: true,
content: content,
helpers: {
title: {
type: 'inside'
}
}
});
}
});
});
And my PHP code is:
function get_ebook_data()
{
$ebkid = $this->input->post('ebookid');
$rs = $this->mod_manajemen->get_ebook_detail($ebkid);
$hasil['id'] = $ebkid;
foreach ($rs as $row) {
$hasil['judul'] = $row->ebook_judul;
$hasil['kategori'] = $row->ebook_cat_id;
$hasil['penerbit'] = $row->ebook_penerbit;
$hasil['terbit'] = $row->ebook_terbit;
$hasil['halaman'] = $row->ebook_halaman;
$hasil['bahasa'] = $row->ebook_bahasa;
$hasil['format'] = $row->ebook_format;
}
$this->output->set_output(json_encode($hasil));
}
$('#graphtype option[value=""]').prop("selected", true);
This works well where #graphtype
is the id of the select tag.
example select tag:
<select name="site" id="site" class="form-control" onchange="getgraph1(this.options[this.selectedIndex].value);">
<option value="" selected>Site</option>
<option value="sitea">SiteA</option>
<option value="siteb">SiteB</option>
</select>
Is old post but here is one simple function what act like jQuery plugin.
$.fn.selectOption = function(val){
this.val(val)
.find('option')
.removeAttr('selected')
.parent()
.find('option[value="'+ val +'"]')
.attr('selected', 'selected')
.parent()
.trigger('change');
return this;
};
You just simple can do something like this:
$('.id_100').selectOption('val2');
Reson why use this is because you change selected satemant into DOM what is crossbrowser supported and also will trigger change to you can catch it.
Is basicaly human action simulation.
<select name="contribution_status_id" id="contribution_status_id" class="form-select">
<option value="1">Completed</option>
<option value="2">Pending</option>
<option value="3">Cancelled</option>
<option value="4">Failed</option>
<option value="5">In Progress</option>
<option value="6">Overdue</option>
<option value="7">Refunded</option>
Setting to Pending Status by value
$('#contribution_status_id').val("2");
You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue]
, so in your case you can select the option and set the selected attribute.
$("div.id_100 > select > option[value=" + value + "]").prop("selected",true);
Where value
is the value you wish to select by.
If you need to removed any prior selected values, as would be the case if this is used multiple times you'd need to change it slightly so as to first remove the selected attribute
$("div.id_100 option:selected").prop("selected",false);
$("div.id_100 option[value=" + value + "]")
.prop("selected",true);
This Works well
jQuery('.id_100').change(function(){
var value = jQuery('.id_100').val(); //it gets you the value of selected option
console.log(value); // you can see your sected values in console, Eg 1,2,3
});
it works for me
$("#id_100").val("val2");
Use the change()
event after selecting the value. From the docs:
If the field loses focus without the contents having changed, the event is not triggered. To trigger the event manually, apply
.change()
without arguments:
$("#select_id").val("val2").change();
More information is at .change().
a simple answer is, at html
<select name="ukuran" id="idUkuran">
<option value="1000">pilih ukuran</option>
<option value="11">M</option>
<option value="12">L</option>
<option value="13">XL</option>
</select>
on jquery, call below function by button or whatever
$('#idUkuran').val(11).change();
it simple and 100% works, coz its taken from my work... :) hope its help..
You can achieve this with different methods:
(remember if an element is to be operated, better give it an id or class, rather than having it's parent element an id or class).
Here,
As the div has a class to target the select inside it, code will be:
$("div.id_100 select").val("val2");
or
$('div.id_100 option[value="val2"]').prop("selected", true);
If the class would have been given to select itself, code will be:
$(".id_100").val("val2");
or
$('.id_100 option[value=val2]').attr('selected','selected');
or
$('.id_100 option')
.removeAttr('selected')
.filter('[value=val1]')
.attr('selected', true);
To pass the value dynamically, code will be:
valu="val2";
$("div.id_100 select").val(valu);
$("div.id_100 > select > option[value=" + valu + "]").prop("selected",true);
If element is added through ajax,
You will have to give 'id' to your element and use
window.document.getElementById
else
You will have to give 'class' to your element and use
window.document.getElementById
You can also select value of select element by it's index number.
If you have given ID to your select element, code will be:
window.document.getElementById('select_element').selectedIndex = 4;
Remember when you change the select value as said above, change method is not called.
i.e. if you have written code to do some stuff on change of select the above methods will change the select value but will not trigger the change.
for to trigger the change function you have to add .change() at the end.
so the code will be:
$("#select_id").val("val2").change();
The easiest way to do that is:
<select name="dept">
<option value="">Which department does this doctor belong to?</option>
<option value="1">Orthopaedics</option>
<option value="2">Pathology</option>
<option value="3">ENT</option>
</select>
$('select[name="dept"]').val('3');
Output: This will activate ENT.
Best way is like this:
$(`#YourSelect option[value='${YourValue}']`).prop('selected', true);
For me the following did the job
$("div.id_100").val("val2").change();
I think the easiest way is selecting to set val(), but you can check the following. See How to handle select and option tag in jQuery? for more details about options.
$('div.id_100 option[value="val2"]').prop("selected", true);
$('id_100').val('val2');
Not optimised, but the following logic is also useful in some cases.
$('.id_100 option').each(function() {
if($(this).val() == 'val2') {
$(this).prop("selected", true);
}
});
There's no reason to overthink this, all you are doing is accessing and setting a property. That's it.
Okay, so some basic dom: If you were doing this in straight JavaScript, it you would this:
window.document.getElementById('my_stuff').selectedIndex = 4;
But you're not doing it with straight JavaScript, you're doing it with jQuery. And in jQuery, you want to use the .prop() function to set a property, so you would do it like this:
$("#my_stuff").prop('selectedIndex', 4);
Anyway, just make sure your id is unique. Otherwise, you'll be banging your head on the wall wondering why this didn't work.
This works for sure for Select Control:
$('select#ddlCountry option').each(function () {
if ($(this).text().toLowerCase() == co.toLowerCase()) {
this.selected = true;
return;
} });
Source Link
Use val() jQuery Method for Single and Multiple Value Selection in DropDown
$(function () {
$("button").click(function () {
$("#myDropDownSingle").val('5');
$("#myDropDownMultiple").val(['5', '4', '8']);
});
});
HTML
<p>
<h5>Single Selection</h5>
<select id="myDropDownSingle" class="form-control">
<option value="0">Select Value 0</option>
<option value="8">Option value 8</option>
<option value="5">Option value 5</option>
<option value="4">Option value 4</option>
</select>
</p>
<p>
<h5>Multiple Selection</h5>
<select id="myDropDownMultiple" class="form-control" multiple>
<option value="0">Select Value 0</option>
<option value="8">Option value 8</option>
<option value="5">Option value 5</option>
<option value="4">Option value 4</option>
</select>
</p>
<p>
<button>Get Value and Text on Button Click</button>
</p>
To select an option with value 'val2':
$('.id_100 option[value=val2]').attr('selected','selected');
There seems to be an issue with select drop down controls not dynamically changing when the controls are dynamically created instead of being in a static HTML page.
In jQuery this solution worked for me.
$('#editAddMake').val(result.data.make_id);
$('#editAddMake').selectmenu('refresh');
Just as an addendum the first line of code without the second line, did actually work transparently in that, retrieving the selected index was correct after setting the index and if you actually clicked the control it would show the correct item but this didn't reflect in the top label of the control.
Hope this helps.
.attr() sometimes doesn't work in older jQuery versions, but you can use .prop():
$('select#ddlCountry option').each(function () {
if ($(this).text().toLowerCase() == co.toLowerCase()) {
$(this).prop('selected','selected');
return;
}
});
An issue I ran into when the value is an ID and the text is a code. You cannot set the value using the code but you don't have direct access to the ID.
var value;
$("#selectorId > option").each(function () {
if ("SOMECODE" === $(this).text()) {
value = $(this).val();
}
});
//Do work here
Just put in this code:
$("#Controls_ID").val(value);
Try this. Simple yet effective javaScript + jQuery the lethal combo.
SelectComponent :
<select id="YourSelectComponentID">
<option value="0">Apple</option>
<option value="2">Banana</option>
<option value="3">Cat</option>
<option value="4">Dolphin</option>
</select>
Selection :
document.getElementById("YourSelectComponentID").value = 4;
Now your option 4 will be selected. You can do this, to select the values on start by default.
$(function(){
document.getElementById("YourSelectComponentID").value = 4;
});
or create a simple function put the line in it and call the function on anyEvent to select the option
A mixture of jQuery + javaScript does the magic....
Deselect all first and filter the selectable options:
$('.id_100 option')
.removeAttr('selected')
.filter('[value=val1]')
.attr('selected', true)
case sensative
. You can change your select box dynamically as follows,$("div#YOUR_ID").val(VALUE_CHANGED).change();
//value must present in options you selected otherwise it will not work
Source: Stackoverflow.com