Reputation: 788
I have a select input created with a value of an observable. I subscribe to the observable, but can't seem to get the ID of the select input.
<select data-bind="options: firstName, optionsText: 'name', value: $parents[0].selectCategory, attr: {'id': lastName}">
</select>
self.selectedCategory.subscribe(function(category) {
console.log(this);
console.log(this.target());
}, this);
I can't for the life of me get the ID of the select element. I can get the value of the options (which aren't set here), and the function that selectedCategory
belongs too, but can't get the ID. I'm pretty sure I could easily do this with just jquery.click, but I'm wondering if I can do it via .subscribe().
Any thoughts or comments?
Upvotes: 0
Views: 1181
Reputation: 2303
I am not pretty sure what you exactly mean by id. And your bindings are a bit messed up. If you mean the id of each selected input, then you can use optionsValue
in your bindings:
<select data-bind="options: names, optionsText: 'name', optionsValue: 'id', value: selectedName, attr: {'id': lastName}">
</select>
self.names = [
{ name: 'Name 1', id: 1},
{ name: 'Name 2', id: 2},
{ name: 'Name 3', id: 3}
];
I left the attr
definition you added even though it technically means nothing just so that you can elaborate more on why you may need it.
If you are interested in getting the id
of each selected element upon change then you can do it this way:
self.selectedName.subscribe(function(name) {
console.log(name);
}, this);
Or of course you can get it upon a button click [in another function] this way:
self.alertName = function(){
alert(self.selectedName());
};
I hope this helps and please let us know if this is what you initially meant.
Upvotes: 1