Steve
Steve

Reputation: 4918

Setting a select element option with a given value to be the selected option

In this jsfiddle - http://jsfiddle.net/3QrC4/3/ - I want to make the option that has the value "Calibri" the selected option. But the last option becomes the selected one. Does anyone see the problem?

Thanks

$(function() {
    $('#fontname option').filter(function() {
        return value="Calibri";
    }).prop('selected', true);
})

Upvotes: 0

Views: 57

Answers (3)

charlietfl
charlietfl

Reputation: 171698

A much simpler approach is just set the value of the <select> using val()

 $('#fontname').val("Calibri");/* pass in array if using a "multiple" select */

If you check the option selected properties it will return the expected results

DEMO

Upvotes: 1

David Sherron
David Sherron

Reputation: 153

Working JSFiddle

Code:

$(function() {
    $('#fontname option').filter(function() {
        return this.value=="Calibri";
    }).prop('selected', true);
})

Inside your filter function, this refers to one element of the set, and the function will be run once per set. Whether the function returns true or false for that element determines whether it should be included in the set.

Note: a=b is the assignment operator, meaning "make a's value the same as b's". a==b is the loose equality operator, meaning "is the value of a equivalent to the value of b?"

Upvotes: 0

Toothbrush
Toothbrush

Reputation: 2141

Try this code (or try it on JSFiddle):

$(function() {
    $('#fontname > option').filter(function() {
        return this.value === 'Calibri';
    }).prop('selected', true);
});

Inside the function, value is not defined.

However, this refers to the current element, so we get the value of it.

Also, you need to use == or === to compare two values in JavaScript.

Upvotes: 1

Related Questions