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 an array of select boxes, with a unique id like this.
<select class="taskcompleted" id="c392018">
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
I have a JSON in the format
{"id":"c392018","value":"Yes"}
I am using the following Javascript to set the selected value
$.getJSON('getstatus.php') //place correct script URL
.done(function(response) {
$.each(response, function(key) {
var SelectObj = response[key];
console.log(SelectObj['value']);
jQuery('#' + SelectObj['id']).val(SelectObj['value']).attr('selected', true);
});
});
This is not selecting the value of "Yes". How can I do this?
You simply need to use .val() to set the selected option using the value from your object:
So where you have:
jQuery('#' + SelectObj['id']).val(SelectObj['value']).attr('selected', true);
Should be:
jQuery('#' + SelectObj['id']).val(SelectObj['value']);
See the snippet example below:
Also if you really want the selected property on the item, you should use:
.prop("selected", "selected");
var SelectObj = {"id":"c392018","value":"Yes"};
jQuery('#' + SelectObj['id']).val(SelectObj['value']).prop('selected','selected');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="taskcompleted" id="c392018">
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
Well, you don't really need jQuery here.
var select = document.getElementById(SelectObj.id);
select.value = SelectObj.value;
<select id="id_deals-1-deal_template" name="deals-1-deal_template">
<option selected="selected" value="">---------</option>
<option value="1" selected="selected">Pear</option>
<option value="2">Apple</option>
<option value="4">Melon</option>
</select>
In order to select Melon I have to do this:
$('#id_deals-1-deal_template>option:eq(3)').prop('selected', true);
But I would rather have to select the primary key that is 4 in this case.
Hence is it possible to select a dropdown by its value rather than sequence?
Try using .val which can be a setter or getter based on the argument. Below is a setter..
$('#id_deals-1-deal_template').val(4);
$('#id_deals-1-deal_template').val(4);
Here is a demo:
http://jsfiddle.net/M3UBc/
use
$('#id_deals-1-deal_template').val(4);
or
$('#id_deals-1-deal_template').val('Melon');
Select by option name
$("#id_deals-1-deal_template option").each(function() {
if($(this).text() == 'Melon') {
$(this).attr('selected', 'selected');
}
});
Select by value id
$("#id_deals-1-deal_template option").each(function() {
if($(this).text() == '4') {
$(this).attr('selected', 'selected');
}
});
I have a select element wrapped by a span element. I am not allowed to use the select id but I am allowed to use the span id.
I am trying to write a javascript/jquery function in which the input is a number i, which is one of the values of the select's options. The function will turn the relevant option to selected.
<span id="span_id">
<select id="h273yrjdfhgsfyiruwyiywer" multiple="multiple">
<option value="1">cleaning</option>
<option value="2">food-2</option>
<option value="3">toilet</option>
<option value="4">baby</option>
<option value="6">knick-knacks</option>
<option value="9">junk-2</option>
<option value="10">cosmetics</option>
</select>
</span>
I wrote something as follows (this does not completely work, which is why I am posting this question):
function select_option(i) {
options = $('#span_id').children('select').children('option');
//alert(options.length); //7
//alert(options[0]); //[object HTMLOptionElement]
//alert(options[0].val()); //not a jquery element
//alert(options[0].value); //1
//the following does not seem to work since the elements of options are DOM ones not jquery's
option = options.find("[value='" + i + "']");
//alert(option.attr("value")); //undefined
option.attr('selected', 'selected');
}
Thanks!
Here's the simplest solution with a clear selector:
function select_option(i) {
return $('span#span_id select option[value="' + i + '"]').html();
}
With jQuery > 1.6.1 should be better to use this syntax:
$('#span_id select option[value="' + some_value + '"]').prop('selected', true);
Just wrap your option in $(option) to make it act the way you want it to. You can also make the code shorter by doing
$('#span_id > select > option[value="input your i here"]').attr("selected", "selected")
options = $("#span_id>select>option[value='"+i+"']");
option = options.text();
alert(option);
here is the fiddle http://jsfiddle.net/hRFYF/
You can use .val() to select the value, like the following:
function select_option(i) {
$("#span_id select").val(i);
}
Here is a jsfiddle: https://jsfiddle.net/tweissin/uscq42xh/8/
To get the value just use this:
<select id ="ari_select" onchange = "getvalue()">
<option value = "1"></option>
<option value = "2"></option>
<option value = "3"></option>
<option value = "4"></option>
</select>
<script>
function getvalue()
{
alert($("#ari_select option:selected").val());
}
</script>
this will fetch the values
function select_option(index)
{
var optwewant;
for (opts in $('#span_id').children('select'))
{
if (opts.value() = index)
{
optwewant = opts;
break;
}
}
alert (optwewant);
}
You can change with simple javascript
document.querySelector('#h273yrjdfhgsfyiruwyiywer').value='4'
<span id="span_id">
<select id="h273yrjdfhgsfyiruwyiywer" multiple="multiple">
<option value="1">cleaning</option>
<option value="2">food-2</option>
<option value="3">toilet</option>
<option value="4">baby</option>
<option value="6">knick-knacks</option>
<option value="9">junk-2</option>
<option value="10">cosmetics</option>
</select>
</span>
$("#h273yrjdfhgsfyiruwyiywer").children('[value="' + i + '"]').prop("selected", true);
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.