Search code examples
ractivejs

Append text to input after selecting one from list


<input type="submit" on-click='toggle("Dropdown")'>
<input type="text" value="{{category.name}}">
{{#if Dropdown}}
  <div class="dropdown">
    <ul>
      <li><a href="#" on-click="select">Custard Pudding</a></li>
      <li><a href="#" on-click="select">Coffee Pudding</a></li>
    </ul>

{{/if}}

ractive.on('select', function(event) {

    this.observe( 'category.name', function ( newValue, keypath ) {
        this.set( keypath, '' + newValue );
    });
})

Understand that in JQuery $('dropdown a').text() and append it to input would work. Only question I have is how to grab the text and set it to input when on-click "select". Searched example and tried but it is not doing anything. Perhaps the way is wrong.

Please help


Solution

  • You can get the value from event.node:

    ractive.on('select', function(event) {
        this.set( 'category.name', '' + event.node.textContent );
    })
    

    You could do that inline too:

    <li><a href="#" on-click="set('category.name', '' + event.node.textContent)">Custard Pudding</a></li>
    

    But if the <li> are generated from data (or you could make it that way) you can set directly

    <input type="submit" on-click='toggle("Dropdown")'>
    <input type="text" value="{{category.name}}">
    {{#if Dropdown}}
      <div class="dropdown">
        <ul>
          {{#each ['Custard Pudding', 'Coffee Pudding'] }}
          <li><a href="#" on-click="set('category.name', this)">{{this}}</a></li>
          {{/each}}
        </ul>
    
    {{/if}}