Reputation: 176
I want to change my select's option when one of my var change.
I start with this.
JS :
test = new Array();
HTML :
<select>
</select>
And I search to change my select when I add element in test like this :
JS :
test.push({value:1,innerHTML:opt1})
test.push({value:2,innerHTML:opt2})
HTML :
<select>
<option value=1>opt1</option>
<option value=2>opt2</option>
</select>
Can I do that with eventlistener or anything else?
Upvotes: 2
Views: 121
Reputation: 82
Try something like this... var tt =['sdfs','sdgfg']; Object.observe(tt, function(){ debugger; }); tt.push('sdfds');
Upvotes: 0
Reputation: 135
You can proxy push method to add your own logic to it:
var test = new Array();
var _push = test.push;
test.push = function(el) {
// add options to select here
_push.call(this, el);
};
Upvotes: 1
Reputation: 3154
There are two ways you can do this:
a) Don't make the variable a simple variable, but an object with a setter function that also executes the DOM changes you want.
function Test() {
var self = this;
self.value = [];
self.set = function(new_obj){
self.value.push(new_obj);
// DOM changes here
}
return self;
}
var test = new Test();
Then when you want to change the variable, write:
test.set({value:1,innerHTML:opt1})
b) Use an mvc framework like knockout.js (which exists to solve this exact problem)
Upvotes: 2
Reputation: 2852
HTML:
<select id="select1" onchange="changeHandler(this)">
<option value="1" >1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
JS:
document.getElementById('select1').value = 2;
function changeHandler(select){
alert(select.value);
}
https://jsfiddle.net/NourSammour/hp9ryekp/1/
and to watch your array and trigger the re-render you can use
Array.observe(test, function(changes) {
// render
});
I hope this help :)
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe
Upvotes: 0