Related
I have a select control, and in a javascript variable I have a text string.
Using jQuery I want to set the selected element of the select control to be the item with the text description I have (as opposed to the value, which I don't have).
I know setting it by value is pretty trivial. e.g.
$("#my-select").val(myVal);
But I'm a bit stumped on doing it via the text description. I guess there must be a way of getting the value out from the text description, but my brain is too Friday afternoon-ed to be able to work it out.
Select by description for jQuery v1.6+
var text1 = 'Two';
$("select option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text1;
}).prop('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
jQuery versions below 1.6 and greater than or equal to 1.4
var text1 = 'Two';
$("select option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text1;
}).attr('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
Note that while this approach will work in versions that are above 1.6 but less than 1.9, it has been deprecated since 1.6. It will not work in jQuery 1.9+.
Previous versions
val() should handle both cases.
$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
I haven't tested this, but this might work for you.
$("select#my-select option")
.each(function() { this.selected = (this.text == myVal); });
Try this...to select the option with text myText
$("#my-Select option[text=" + myText +"]").prop("selected", true);
I do it on this way (jQuery 1.9.1)
$("#my-select").val("Dutch").change();
Note: don't forget the change(), I had to search to long because of that :)
$("#myselect option:contains('YourTextHere')").val();
will return the value of the first option containing your text description. Tested this and works.
To avoid all jQuery version complications, I honestly recommend using one of these really simple javascript functions...
function setSelectByValue(eID,val)
{ //Loop through sequentially//
var ele=document.getElementById(eID);
for(var ii=0; ii<ele.length; ii++)
if(ele.options[ii].value==val) { //Found!
ele.options[ii].selected=true;
return true;
}
return false;
}
function setSelectByText(eID,text)
{ //Loop through sequentially//
var ele=document.getElementById(eID);
for(var ii=0; ii<ele.length; ii++)
if(ele.options[ii].text==text) { //Found!
ele.options[ii].selected=true;
return true;
}
return false;
}
This line worked:
$("#myDropDown option:contains(myText)").attr('selected', true);
I know this is an old post, but I couldn't get it to select by text using jQuery 1.10.3 and the solutions above.
I ended up using the following code (variation of spoulson's solution):
var textToSelect = "Hello World";
$("#myDropDown option").each(function (a, b) {
if ($(this).html() == textToSelect ) $(this).attr("selected", "selected");
});
Hope it helps someone.
$("#Test").find("option:contains('two')").each(function(){
if( $(this).text() == 'two' ) {
$(this).attr("selected","selected");
}
});
The if statement does a exact match with "two" and "two three" will not be matched
Easiest way with 1.7+ is:
$("#myDropDown option:text=" + myText +"").attr("selected", "selected");
1.9+
$("#myDropDown option:text=" + myText +"").prop("selected", "selected");
Tested and works.
Here is very simple way. plz use it
$("#free").val("y").change();
take a look at the jquery selectedbox plugin
selectOptions(value[, clear]):
Select options by value, using a string as the parameter $("#myselect2").selectOptions("Value 1");, or a regular expression $("#myselect2").selectOptions(/^val/i);.
You can also clear already selected options: $("#myselect2").selectOptions("Value 2", true);
Just on a side note. My selected value was not being set. And i had search all over the net. Actually i had to select a value after a call back from a web service, because i was getting data from it.
$("#SelectMonth option[value=" + DataFromWebService + "]").attr('selected', 'selected');
$("#SelectMonth").selectmenu('refresh', true);
So the refresh of the selector was was the only thing that i was missing.
I found that by using attr you would end up with multiple options selected when you didn't want to - solution is to use prop:
$("#myDropDown option:text=" + myText +"").prop("selected", "selected");
I had a problem with the examples above, and the problem was caused by the fact that my select box values are prefilled with fixed length strings of 6 characters, but the parameter being passed in wasn't fixed length.
I have an rpad function which will right pad a string, to the length specified, and with the specified character. So, after padding the parameter it works.
$('#wsWorkCenter').val(rpad(wsWorkCenter, 6, ' '));
function rpad(pStr, pLen, pPadStr) {
if (pPadStr == '') {pPadStr == ' '};
while (pStr.length < pLen)
pStr = pStr + pPadStr;
return pStr;
}
$('#theYear').on('change', function () {
FY = $(this).find('option:selected').text();
$('#theFolders').each(function () {
$('option:not(:contains(' + FY + '))', this).hide();
});
$('#theFolders').val(0);
});
$('#theYear').on('mousedown', function () {
$('#theFolders option').show().find('option:contains("Select")', this).attr('selected', 'selected');
});
Very fiddly and nothing else seemed to work
$('select[name$="dropdown"]').children().text("Mr").prop("selected", true);
worked for me.
Try
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
<select id="mySelect">
<option value="A">Text A</option>
<option value="B">Text B</option>
<option value="C">Text C</option>
</select>
This accepted answer does not seem correct, while .val('newValue') is correct for the function, trying to retrieve a select by its name does not work for me, I had to use the id and classname to get my element
Heres an easy option. Just set your list option then set its text as selected value:
$("#ddlScheduleFrequency option").selected(text("Select One..."));
If you are trying to bind select with ID then the following code worked for me.
<select name="0product_id[]" class="groupSelect" id="groupsel_0" onchange="productbuilder.update(this.value,0);">
<option value="0" class="notag" id="id0_0">--Select--</option>
<option class="notag" value="338" id="id0_338" >Dual Promoter Puromycin Expression Plasmid - pSF-CMV-PGK-Puro > £114.00</option>
<option class="notag" value="282" id="id0_282" >EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro > £114.00</option>
<option class="notag" value="265" id="id0_265" >FMDV IRES Puromycin Expression Plasmid - pSF-CMV-FMDV-Puro > £114.00</option>
<option class="notag" value="101" id="id0_101" >Puromycin Selection Plasmid - pSF-CMV-Ub-Puro AscI > £114.00</option>
<option class="notag" value="105" id="id0_105" >Puromycin Selection SV40 Ori Plasmid - pSF-CMV-Ub-Puro-SV40 Ori SbfI > £114.00</option></select>
AND THIS IS TEH JS CODE
$( document ).ready(function() {
var text = "EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro > £114.00";
alert(text);
$("#groupsel_0 option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text;
}).prop('selected', true);
});
Get the children of the select box; loop through them; when you have found the one you want, set it as the selected option; return false to stop looping.
I have a dropdown box (Sub District) and a "listbox_source" (villages). I prepare value for the dropdown and listbox from sql server and listbox's values depend on drop down, dynamic.
Then, I have another "listbox_destination" for moving selected village from "listbox_source". I've done for moving value from listbox_source to listbox_destination.
but, then, there is questions,
how do I know if listbox_destination still empty or has values ?
how do I know if there is no double value in listbox_destination
when Sub District dropdown was selected for the second time and with
the same value ?
Please, advice...
I try give an example of my code:
Dropdown:
<select id="ID_Villages" size="10" multiple="">
<option value="42">Bandul</option>
<option value="43">Dedap</option>
<option value="44">Mekar Delima</option>
<option value="45">Putri Puyu</option>
<option value="46">Tanjung Padang</option>
<option value="47">Tanjung Pisang</option>
<option value="187">Kudap</option>
<option value="188">Selat Akar</option>
<option value="189">Mengkopot</option>
<option value="190">Mengkirau</option>
$(document).ready(function (e) {
$('#btn_To_Right').click(function (e) {
var selectedList = $('#ID_Villages option:selected').toArray();
if ($('selectedList').length == 0) {
alert("Nothing to move.");
e.preventDefault();
} else {
<!-- #1. how to check listbox_destination still empty or has values ? -->
$(selectedVillage).append($(selectedList).clone());
$(selectedList).remove();
alert(selectedVillage.length);
} else {
<!-- #2. how to avoid double values -->
$each(selectedList, function (index, value) {
if($selectedVillage ??? ).length == 0){
<!-- add new value -->
} else {
alert ("data already exist");
}
}
}
}
})
})
UPDATE
for first moving (#1), from listbox_source to listox_destination, I check listox_destination by using
if ($("#lst_ID_Desa_Selected option").length == 0) {
$(selectedVillage).append($(selectedList).clone());
$(selectedList).remove();
}
and then for double values protection (#2)
$.each(selectedList, function (index, value) {
alert($("selectedList option[value='" + 42 + "']").length);
alert($("selectedList option[value='" + value.value + "']"));
alert($("selectedList <option value='" + value.value + "'>"));
})
I tried to get value from
alert($("selectedList option[value='" + value + "']").length);
by using alert but popup value appears "0". Whereas, selectedList is the source data of villages.
I tried to get value from
alert($("selectedList option[value='" + value.value + "']"));
by using alert and the return value as [object Object]
while I tried to get value from
alert($("selectedList <option value='" + value.value + "'>"));
there is error message:
syntax error, unrecognized expression: selectedList <option value='42'>
I think, I have to check selectList syntax before I use it for if under $.each syntax.
Please, I need further advice for this JS/jQuery syntax.
To find whether list is empty or not, is can be done using the following code after $(selectedList).remove();
$("#ID_Villages option").length; //If 0 then no options in the select list
To check for duplicates, you can use something like:
$("selectedDesa option[value='42']").length;
If the value of above is 0 then no option found in the destination list. If the length is 1 then option already exists. You can replace the value attribute based on the selected option value from the source list.
Update:
There is no need to loop. You can use the logic as below:
var selectedList = $('#ID_Villages option:selected').toArray();
var selectedVal = $('#ID_Villages option:selected').val(); // New code
Then while checking for duplicates, use the below:
$("selectedDesa option[value='" + selectedVal + "']").length;
// In jquery
$('.check').val('two').trigger('change');
// and html is
<select class="check">
<option value="one">First</option>
<option value="two">Second</option>
</select>
http://jsfiddle.net/v7QWd/353/
I need trigger the event using my text value i.e. "First" in jquery. Any solution of it? Here I have used .val('two') instead I wish to use "First"..
I think what you are trying to do is to select the option by its text, if so you can use :contains() - but it can give expected matches since it will use partial matches
So try
$(function() {
$('.check').change(function() {
var data = $(this).val();
snippet.log('data:' + data)
//if you want the selected text
var text = $(this).find('option:selected').text();
snippet.log('text:' + text)
});
$('.check option').filter(function() {
return $(this).text() == 'Second'
}).prop('selected', true)
$('.check').trigger('change');
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="check">
<option value="one">First</option>
<option value="two">Second</option>
</select>
if ($('.check option:selected').text() == "First") {
$('.check').trigger('change');
}
$(function () {
//change to two ? how?
$('.check').change(function () {
var data = $(this).val();
alert(data);
});
if ($('.check option:selected').text() == "First") {
$('.check').trigger('change');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="check">
<option value="one">First</option>
<option value="two">Second</option>
</select>
Use .text() to get the selected option text and .change() to trigger initially on load
$('.check').change(function(){
var data= $(this).find("option:selected").text();
if(data == 'First'){
// your logic
}
}).change();
Fiddle
How can you get the selected value from drop down list using JavaScript? I have tried the following but it does not work.
var sel = document.getElementById('select1');
var sv = sel.options[sel.selectedIndex].value;
alert(sv);
It is working fine with me.
I have the following HTML:
<div>
<select id="select1">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
<br/>
<button onClick="GetSelectedItem('select1');">Get Selected Item</button>
</div>
And the following JavaScript:
function GetSelectedItem(el)
{
var e = document.getElementById(el);
var strSel = "The Value is: " + e.options[e.selectedIndex].value + " and text is: " + e.options[e.selectedIndex].text;
alert(strSel);
}
See that you are using the right id. In case you are using it with ASP.NET, the id changes when rendered.
Direct value should work just fine:
var sv = sel.value;
alert(sv);
The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.
Hope it's working for you
function GetSelectedItem()
{
var index = document.getElementById(select1).selectedIndex;
alert("value =" + document.getElementById(select1).value); // show selected value
alert("text =" + document.getElementById(select1).options[index].text); // show selected text
}
Here is a simple example to get the selected value of dropdown in javascript
First we design the UI for dropdown
<div class="col-xs-12">
<select class="form-control" id="language">
<option>---SELECT---</option>
<option>JAVA</option>
<option>C</option>
<option>C++</option>
<option>PERL</option>
</select>
Next we need to write script to get the selected item
<script type="text/javascript">
$(document).ready(function () {
$('#language').change(function () {
var doc = document.getElementById("language");
alert("You selected " + doc.options[doc.selectedIndex].value);
});
});
Now When change the dropdown the selected item will be alert.
I would say change var sv = sel.options[sel.selectedIndex].value;
to var sv = sel.options[sel.selectedIndex].text;
It worked for me. Directing you to where I found my solution
Getting the selected value dropdown jstl
According to Html5 specs you should use --
element.options[e.selectedIndex].text
e.g. if you have select box like below :
<select id="selectbox1">
<option value="1">First</option>
<option value="2" selected="selected">Second</option>
<option value="3">Third</option>
</select>
<br/>
<button onClick="GetItemValue('selectbox1');">Get Item</button>
you can get value using following script :
<script>
function GetItemValue(q) {
var e = document.getElementById(q);
var selValue = e.options[e.selectedIndex].text ;
alert("Selected Value: "+selValue);
}
</script>
Tried and tested.
I have a select control, and in a javascript variable I have a text string.
Using jQuery I want to set the selected element of the select control to be the item with the text description I have (as opposed to the value, which I don't have).
I know setting it by value is pretty trivial. e.g.
$("#my-select").val(myVal);
But I'm a bit stumped on doing it via the text description. I guess there must be a way of getting the value out from the text description, but my brain is too Friday afternoon-ed to be able to work it out.
Select by description for jQuery v1.6+
var text1 = 'Two';
$("select option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text1;
}).prop('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
jQuery versions below 1.6 and greater than or equal to 1.4
var text1 = 'Two';
$("select option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text1;
}).attr('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
Note that while this approach will work in versions that are above 1.6 but less than 1.9, it has been deprecated since 1.6. It will not work in jQuery 1.9+.
Previous versions
val() should handle both cases.
$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
I haven't tested this, but this might work for you.
$("select#my-select option")
.each(function() { this.selected = (this.text == myVal); });
Try this...to select the option with text myText
$("#my-Select option[text=" + myText +"]").prop("selected", true);
I do it on this way (jQuery 1.9.1)
$("#my-select").val("Dutch").change();
Note: don't forget the change(), I had to search to long because of that :)
$("#myselect option:contains('YourTextHere')").val();
will return the value of the first option containing your text description. Tested this and works.
To avoid all jQuery version complications, I honestly recommend using one of these really simple javascript functions...
function setSelectByValue(eID,val)
{ //Loop through sequentially//
var ele=document.getElementById(eID);
for(var ii=0; ii<ele.length; ii++)
if(ele.options[ii].value==val) { //Found!
ele.options[ii].selected=true;
return true;
}
return false;
}
function setSelectByText(eID,text)
{ //Loop through sequentially//
var ele=document.getElementById(eID);
for(var ii=0; ii<ele.length; ii++)
if(ele.options[ii].text==text) { //Found!
ele.options[ii].selected=true;
return true;
}
return false;
}
This line worked:
$("#myDropDown option:contains(myText)").attr('selected', true);
I know this is an old post, but I couldn't get it to select by text using jQuery 1.10.3 and the solutions above.
I ended up using the following code (variation of spoulson's solution):
var textToSelect = "Hello World";
$("#myDropDown option").each(function (a, b) {
if ($(this).html() == textToSelect ) $(this).attr("selected", "selected");
});
Hope it helps someone.
$("#Test").find("option:contains('two')").each(function(){
if( $(this).text() == 'two' ) {
$(this).attr("selected","selected");
}
});
The if statement does a exact match with "two" and "two three" will not be matched
Easiest way with 1.7+ is:
$("#myDropDown option:text=" + myText +"").attr("selected", "selected");
1.9+
$("#myDropDown option:text=" + myText +"").prop("selected", "selected");
Tested and works.
Here is very simple way. plz use it
$("#free").val("y").change();
take a look at the jquery selectedbox plugin
selectOptions(value[, clear]):
Select options by value, using a string as the parameter $("#myselect2").selectOptions("Value 1");, or a regular expression $("#myselect2").selectOptions(/^val/i);.
You can also clear already selected options: $("#myselect2").selectOptions("Value 2", true);
Just on a side note. My selected value was not being set. And i had search all over the net. Actually i had to select a value after a call back from a web service, because i was getting data from it.
$("#SelectMonth option[value=" + DataFromWebService + "]").attr('selected', 'selected');
$("#SelectMonth").selectmenu('refresh', true);
So the refresh of the selector was was the only thing that i was missing.
I found that by using attr you would end up with multiple options selected when you didn't want to - solution is to use prop:
$("#myDropDown option:text=" + myText +"").prop("selected", "selected");
I had a problem with the examples above, and the problem was caused by the fact that my select box values are prefilled with fixed length strings of 6 characters, but the parameter being passed in wasn't fixed length.
I have an rpad function which will right pad a string, to the length specified, and with the specified character. So, after padding the parameter it works.
$('#wsWorkCenter').val(rpad(wsWorkCenter, 6, ' '));
function rpad(pStr, pLen, pPadStr) {
if (pPadStr == '') {pPadStr == ' '};
while (pStr.length < pLen)
pStr = pStr + pPadStr;
return pStr;
}
$('#theYear').on('change', function () {
FY = $(this).find('option:selected').text();
$('#theFolders').each(function () {
$('option:not(:contains(' + FY + '))', this).hide();
});
$('#theFolders').val(0);
});
$('#theYear').on('mousedown', function () {
$('#theFolders option').show().find('option:contains("Select")', this).attr('selected', 'selected');
});
Very fiddly and nothing else seemed to work
$('select[name$="dropdown"]').children().text("Mr").prop("selected", true);
worked for me.
Try
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
<select id="mySelect">
<option value="A">Text A</option>
<option value="B">Text B</option>
<option value="C">Text C</option>
</select>
This accepted answer does not seem correct, while .val('newValue') is correct for the function, trying to retrieve a select by its name does not work for me, I had to use the id and classname to get my element
Heres an easy option. Just set your list option then set its text as selected value:
$("#ddlScheduleFrequency option").selected(text("Select One..."));
If you are trying to bind select with ID then the following code worked for me.
<select name="0product_id[]" class="groupSelect" id="groupsel_0" onchange="productbuilder.update(this.value,0);">
<option value="0" class="notag" id="id0_0">--Select--</option>
<option class="notag" value="338" id="id0_338" >Dual Promoter Puromycin Expression Plasmid - pSF-CMV-PGK-Puro > £114.00</option>
<option class="notag" value="282" id="id0_282" >EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro > £114.00</option>
<option class="notag" value="265" id="id0_265" >FMDV IRES Puromycin Expression Plasmid - pSF-CMV-FMDV-Puro > £114.00</option>
<option class="notag" value="101" id="id0_101" >Puromycin Selection Plasmid - pSF-CMV-Ub-Puro AscI > £114.00</option>
<option class="notag" value="105" id="id0_105" >Puromycin Selection SV40 Ori Plasmid - pSF-CMV-Ub-Puro-SV40 Ori SbfI > £114.00</option></select>
AND THIS IS TEH JS CODE
$( document ).ready(function() {
var text = "EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro > £114.00";
alert(text);
$("#groupsel_0 option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text;
}).prop('selected', true);
});
Get the children of the select box; loop through them; when you have found the one you want, set it as the selected option; return false to stop looping.