0

Someone can tell me why my code doesn't work please ??

I get "this.username is undefined" and i don't really understand why...

Here the code :

riot.tag2('test', '<input type="text" name="username" placeholder="username" oninput={validate} value="" /> <h4>{username_valid}</h4>', '', '', function(opts) {
    this.validate = function(e) {
        this.username_valid = (this.username.value.length > 3) ? 'Valid' : 'Invalid'
    };
});

Thanks for your help..

Ravaniss
  • 21
  • 1
  • 1
  • 8
  • Which Riot version are you using? If you are using v3, you need to use refs to reference the variables. So in the input, you should have ref="username" and in the method this.refs.username.value . http://riotjs.com/guide/#named-elements – vitomd Feb 08 '17 at 23:49

1 Answers1

3

Just because it's so hard to read, I hope you're not actually writing the component using the riot API. I transcribed it into a tag so we can have a better look:

<test>

  <input
    type="text"
    name="username"
    placeholder="username"
    oninput={validate}
    value=""/>

  <h4>{username_valid}</h4>

  <script>

    this.validate = function(e) {
        this.username_valid = (this.username.value.length > 3) ? 'Valid' : 'Invalid'
    }

  </script>
</test>

You're trying to get username from the input element. this in a tag refers to the scope of the script, not the DOM elements. There are a few ways you can get the input value

  1. Add ref='username' to the <input> tag.
    Then use this.refs.username.value to get the value from a ref

  2. In the validate function, use e.target.value to get the element from the oninput event

  3. Use this.root.querySelectorAll('input')[0].value for a scoped DOM query