I am attempting to set an option in a dropdown/select. I have done this before, but for some reason I am getting an error and I am not sure why.
Code
var _loc = {
ALL_BUYS: [{ Text: "All Buys", Value: "AAA"}],
NETWORK_BREAK: [{ Text: "Network Break", Value: "NTN"}],
SYNDICATED_BREAK: [{ Text: "Syndicated Break", Value: "STA"}],
LOCAL_BREAK: [{ Text: "Local Break", Value: "LTA"}],
NATIONAL_LOCAL: [{ Text: "National/Local", Value: "LTN"}],
LOCAL_LOCAL: [{ Text: "Local/Local", Value: "LTL"}]//,
};
lstOptions = $("<select></select>");
$.each(_loc, function (i, item)
{
$("<option></option>")
.appendTo(lstOptions)
.html(item.Text)
.val(item.Value) // receive error: Object has no method 'val'
});
You’re not grabbing the values from the object correctly.
The format is like so:
When you use
$.each, it selects each one in this state:On the first iteration, it would select the value associated with key1, on the second, key2, etc.
Since you have arrays nested in each key’s value, you need to specify that it locate the first array in the matched value:
Demo.
Note the
item[0]. What this does is select the array with the index0in the value that it grabbed. Since there is only one, that single array’s index is0, so it’s selecting that specific one. Then you find and set its text and value.Also note that I changed
val()toattr(), becauseoptionelements don’t supportval()(you could, however, use it on aselectelement to set the option whose value is equal to the one specified in this function to make it selected).TIP: You could also get rid of the literal array indicators around each nested object and use the original method. Demo.