Set option with particular text in select using jquery [duplicate] - javascript
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.
Related
form select option dynamic attr
I need to make Select name with option value, to select a specific value or index. the data where comes from db in a value "{{design}}". I do get the value currectly, but I dont manage to set "selected" on the currect option value. here is the code: console.log("{{design}}"); $(document).ready(function () { var options = $('select').children('option'); var size = $('select').children('option').length; for (i=0;i<size;i++) { if ( options[i].innerHTML==="{{design}}") { options.selectedIndex=i; } } }); the html is : <select name="design" required id="design" > <option value="1">flowers</option> <option value="2">classic</option> <option value="3">roses</option> </select> I need to make to currect {{design}} value, lets say it's 2, so it will be <option value="2" selected>classic</option>` thanks! SOLVED Hi, found the solution to the issue, if anyone eles goes into trouble. $(document).ready(function () { var options = $('select').children('option'); var size = $('select').children('option').length; for (i=0;i<size;i++) { if ( $('select').children('option')[i].value === "{{design}}") { $('select').children('option')[i].selected=true; } } }); the currect way is to find the right option value and then-> [i].selected=true goodluck
Try this var selectedvalue=2; //option with value 2 should be selected $("#design option[value=selectedvalue]").attr("selected","selected"); Hope this helps...
If I understood right, you are on the right path just taking a minor detour. Try this: if ( options[i].innerHTML==="{{design}}") { options.attr('selected', 'selected'); } The example of .each() usage: $(document).ready(function(){ $('select option').each(function(i){ if( i.value === "{{design}}"){ $(this).attr('selected','selected'); } }); });
try this: $(document).ready(function(){ $('select option').each(function(i){ //if this option contains the word "{{design}}" Then this is selected if( $(this).html().indexOf("{{design}}") != -1) $(this).attr('selected',true); }); });
jquery get select option value and then add parameter
I'm trying to add on to the value "&fullpage=true" <select name="navMenu" onchange="go(this.options[this.selectedIndex].value)"> <option value="-">Select</option> <option value="page.html&nyo=0" class="ccbnLnk">All</option> <option value="page.html&nyo=0" class="ccbnLnk">IR</option> <option value="page.html&nyo=0" class="ccbnLnk">Product</option> </select> I'm guessing it would be something like this? $('select option').attr(val + "&fullpage=true");
You were close, but you needed to iterate over all the option elements and then make the change like: $('select option').each(function () { $(this).val($(this).val() + "&fullpage=true"); }); jsFiddle example
You can loop through each of the element using the each function $('select option').each(function(){ $(this).attr('value', $(this).attr('value') + "&fullpage=true"); });
jQuery select option elements by value
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);
Selecting an option in a dropdown menu based on node value?
Is there a way to set the value of a dropdown list in jQuery (or Javascript) based on the node value? <select name="ddlProperty"> <option value="1" selected="selected"></option> <option value="2">Animal Kingdom</option> <option value="3">Epcot</option> <option value="4">Hollywood Studios</option> <option value="5">Magic Kingdom</option> <option value="6">Downtown Disney</option> </select> I'd need to set the option of Magic Kingdom, so something like: $("#ddlLocation").val("Magic Kingdom") So that Magic Kingdom would become the selected item, that doesn't work as expected. Any ideas?
If you can use the value (not text!), do that using .val(): $("#ddlProperty").val("5"); If you don't have that, use .filter(), .text() and .attr() to find and set the selected <option>, like this: $("#ddlProperty option").filter(function() { return $(this).text() === "Magic Kingdom" }).attr('selected', true);
Something like: var box = document.getElementById('box'), options = box.options; for(var i = 0; i < options.length; ++i){ if(options[i].text == val){ options[i].selected = true; } }
$("#ddlProperty > option").each(function(i, elem) { if($(elem).text() == "Magic Kingdom") { $('#ddlProperty').val(elem.value); return false; } }); And next time please make a proper example where the element has an id and that ID matches the ID in your code. I've spent about 5 minutes checking for an error until I've noticed the ID being different... http://jsbin.com/ikibi3/2
myselect="Magic Kingdom"; $("select[name='ddlProperty'] option").each(function() { if($(this).text() == myselect) { $(this).attr('selected', true); } else { $(this).attr('selected', false); } });
jQuery - setting the selected value of a select control via its text description
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.