Tauren
Tauren

Reputation: 27243

Creating DOM 'option' elements with 'selected' attribute

Why does this code would work fine in jQuery 1.5 and not in jQuery 1.6? Was there a known change to how jquery creates DOM nodes between these two versions?

var birth = new Date(),
    current = new Date().getFullYear() - 13,
    year = $('select#year'),
    i = 0;
birth.setFullYear(1992, 10, 3);
while (i < 48) {
    var option = $('<option>', { 
        value: current - i,
        text: current - i,
        selected: (current - i === birth.getFullYear()) ? 'selected' : ''
    });
    year.append(option);
    i++;
}

See this working jsfiddle using 1.5 and this non-working jsfiddle using 1.6. The first only selects one option, but the second adds selected="selected" to every option.

Note I've only tested this in Chrome at this point.

Upvotes: 1

Views: 405

Answers (2)

Rafay
Rafay

Reputation: 31043

set the else part to false

var birth = new Date(),
    current = new Date().getFullYear() - 13,
    year = $('select#year'),
    i = 0;
birth.setFullYear(1992, 10, 3);
while (i < 48) {
    var option = $('<option>', {
        value: current - i,
        text: current - i,
        selected: ((current - i) === (birth.getFullYear())) ? 'selected' :false
    });
    year.append(option);
    i++;
}

here is the fiddle http://jsfiddle.net/Z7umc/4/

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 220146

selected: (current - i === birth.getFullYear()) ? 'selected' : ''

will generate either

selected="selected"

or

selected=""

In both of these cases, the browser considers selected set. That's because selected is a Boolean; Its mere presence signals that it should be selected.

You should use prop, which was introduced in jQuery 1.6:

var option = $('<option>', { 
        value: current - i,
        text: current - i
    }).prop('selected', current - i === birth.getFullYear());

http://jsfiddle.net/Z7umc/3/

Or, if you prefer to have it all within your object:

var option = $('<option>', { 
        value: current - i,
        text: current - i,
        selected: (current - i === birth.getFullYear())
    });

Upvotes: 4

Related Questions