user967451
user967451

Reputation:

Is there a shorter way to write this Jquery code?

If I need to preselect a dropdown option with a certain value, I can use this:

$('select option[value="123"]').attr('selected', 'selected');

but if I need to preselect an option based on the text it contains I need to do all this:

        $('select option').each(function() {
            var $this = $(this);
            if($this.text() == 'My Text') {
                $this.attr('selected', 'selected');
            }
        });

Is there a way to do it without looping through all the option tags like the first way but based on text instead of value?

Upvotes: 1

Views: 77

Answers (4)

elclanrs
elclanrs

Reputation: 94131

I would use filter() which I think will be faster than the :contains selector:

$('select option')
  .filter(function(){ return $(this).text() === 'my text' })
  .prop('selected', true)

Upvotes: 0

Leonid
Leonid

Reputation: 3171

Putting :contains aside

$('select option').each(function() {
    this.selected = this.text == 'lol2'
});

Upvotes: 0

Christian
Christian

Reputation: 19750

Use the :contains selector. Eg:

$('select option:contains("My Text")').attr('selected', 'selected');

Upvotes: 1

Brad
Brad

Reputation: 163593

Check out the :contains() selector.

http://api.jquery.com/contains-selector/

$('select option:contains("My Text")').prop('selected', true);

Upvotes: 2

Related Questions