2
<select class='selb' id='selbauth' >

this works:

$('#selbauth option[value="abc"]').attr('selected','selected');

the same but selecting not by value but by text - doesn't work:

$('#selbauth option[text="lorem"]').attr('selected','selected');

I tried another way:

function selbytext(dd, txt){
for (var i = 0; i < dd.options.length; i++) {
    if (dd.options[i].text == txt) {
        dd.selectedIndex = i;
        break;
    }
}}

selbytext($('#selbauth'), 'lorem');

error:
Cannot read property 'length' of undefined

Any help?

4 Answers4

3

Here you go with a solution https://jsfiddle.net/5rc49waj/

$('#selbauth option:contains("abc")').attr('selected','selected');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class='selb' id='selbauth' >
  <option>Test 1</option>
  <option>abc</option>
</select>

I've used jQuery contains.

Reference Document: https://api.jquery.com/jQuery.contains/

If you are using jQuery version greater than 1.6 then use prop instead of `attr.

$('#selbauth option:contains("abc")').prop('selected','selected');

Hope this will help you.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
1

text is not an attribute. Use :contains to search the text contents of an element.

$("#selbauth option:contains(abc)").prop('selected', true);

Also see .prop() vs .attr() for why I used .prop instead of .attr.

The reason your second code didn't work is because dd is a jQuery object, not a DOM element. It would have worked if you'd written.

selbytext($('#selbauth').get(0), 'lorem');
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can use the contains for achieving this:

$(document).ready(function(){
var selectText = 'Audi';
  $('#test option:contains('+selectText+')').attr('selected','selected');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='test'>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

You can use contains as @Shiladitya show you if the text you're searching can't be a substring of another option. If you need an exact match, you can use filter...

$('#selbauth option').filter(function () {
    return $(this).html() == "lorem"; 
}).attr('selected','selected');

I hope it helps

A. Iglesias
  • 2,625
  • 2
  • 8
  • 23