How to set ReactiveVar with value of "input text"?

I want to set reactive value of input box

// Template
<template name="myTpl">
   <input type="text" id="myVal" value={{myVal}}>

   <select id="mySelect">
      <option>.........
   </select>
</template>

// Js
var myVal = ReactiveVar(0);
Template.myTpl.helper({
   myVal: function(){
      return myVal.get();
   }
});

Template.myTpl.events({
   'change .mySelect': function(e, t){
     myVal.set(100);
  }
})

1- input text = 0 // for the first time
2- input text = 100 // when change the select box for the first time
3- I change the input text = 500 by manual
4- And then I change the select box again, but input text still store the old 500 (don’t 100)

cause you never changed myVal when typing in input text, so when it have 500 and you try to assign it 500, it will not invalidate.

you need to monitor also change (keyup) on input text and set myValue to it’s value. It is not 2way binding.

Thanks for your explain.
I will try.

This works

Template.hello.onCreated(function(){
    this.reactive_var = new ReactiveVar(0);
  });

  Template.hello.helpers({
    counter: function () {
      return Session.get('counter');
    },
    reactive_var: function(){
      return Template.instance().reactive_var.get();
    }
  });

  Template.hello.events({
    'click button': function (e,t) {
      // increment the counter when button is clicked
      Session.set('counter', Session.get('counter') + 1);
      // set reactive_var
      t.reactive_var.set(100);
    },
    'change input': function(e,t) {
      t.reactive_var.set(e.target.value);
    }
  });
1 Like

I believe you need to change your selector in your events.

You’re listening for a class instead of an id.

Template.myTpl.events({
   'change #mySelect': function(e, t){ // Change this
     myVal.set(100);
  }
})

This is the pattern I’m using with ReactiveVars too.

Look great, It work fine.
Thanks all :smiley: