Megaroeny
Megaroeny

Reputation: 827

Add disabled selected option in select menu via jQuery

We have a select menu that is being populated via data- attributes and a knockout.js array. I'm not so familiar with jQuery as well, keep this in mind.

How could I add an option via jQuery that is the first selected one and it's disabled as well. Basically, it's being used as a placeholder. I know how to do this via HTML, but not in this way. Here is the HTML that is being used:

<select id="delemilter" data-bind="options: delimiterList, value: delimiterSelectedValue, optionsValue: 'value', optionsText: 'name', enable: true"></select>

In other select menus, one of our developers used this line of jQuery. Seems to be some knockout API stuff. Looks like an observable array:

self.selectMenuID.push({ value: 'Placeholder Text', key: 0, data: 0, disabled: true });

Can't figure out how to reuse this again... Hopefully this is enough information.

Thank you!

Upvotes: 3

Views: 5176

Answers (2)

renatodamas
renatodamas

Reputation: 19595

I find this way much more elegant & readable:

$("select").append($("<option>", {
    value: "foo",
    text: "bar"
}).prop("disabled", true));

Upvotes: 0

TResponse
TResponse

Reputation: 4125

You can do this as follows:

$('#delemilter').prepend('<option disabled="disabled">My disabled Option</option>');

Remember to specify other attributes in our option's html as required.

Here is a JSFiddle for you: http://jsfiddle.net/loanburger/ask9L71h/

Upvotes: 4

Related Questions