javascriptmithril.js

How to use 'value' of input tag in mithril.js


I want to be able to store the value of the text inputted in a variable. I thought something like would work:

m('input', {
    placeholder: 'Type to search...',
    oninput: () => { alert(this.value) }
})

I used alert() just to test it. Whenever an input was given it just gave a message "undefined".


Solution

  • Arrow functions () => {} don't have a this. In order to rely on event handlers binding this to the element firing the event, you'd have to use:

    // the traditional function form...
    m('input', {
        placeholder: 'Type to search...',
        oninput: function(){ alert(this.value) }
    })
    
    // ...or the modern method shorthand:
    m('input', {
        placeholder: 'Type to search...',
        oninput(){ alert(this.value) }
    })
    

    Alternatively you can avoid this altogether (it is ambiguous after all, as we've just seen), keep the arrow function, and use the event object supplied as the first argument to the event handler:

    m('input', {
        placeholder: 'Type to search...',
        oninput: e => { alert(e.target.value) }
    })