Pakk Pakk - 2 months ago 17
Javascript Question

jQuery bug in .append with ternary `:?` operators?

using

var states = {
Abbreviation: "AR",
Name: "Arkansas"
}


Why will this work.

$.each(states, function () {
var o = {
value: this.Abbreviation,
text: this.Name
}

if (this.Abbreviation === "AR") { //hardcoded for you pleasure
o.selected = 'selected';
}

e.append(
$('<option/>', o)
);
});


But not this:

$.each(states, function () {
e.append(
$('<option/>', {
value: this.Abbreviation,
text: this.Name,
selected: (this.Abbreviation === csc.statesDDL.txt().val() ? 'selected' : '')
})
);
});


Are there restrictions to .append within jquery for ternary
:?
operators?

Notes: I have a logged the output of the if statements, when running the commented out code it shows ALL options as selected, the the logs output only 1 options = true. The uncommitted out code, behaves as expected.

Answer

It's not the ternary that's the issue, it appears to be how jQuery/HTML is handling the empty string. jQuery is most likely not resolving the property to an explicit false and thus creating an element with a "selected=''" which the browser may just be interpreting as "selected" which I believe is from an old HTML standard that recognized that as being selected. If you make the false explicit it will work:

                        selected: (this.Abbreviation === csc.statesDDL.txt().val() ? 'selected' : false)
Comments