1

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".

Barney
  • 16,181
  • 5
  • 62
  • 76
Sujit
  • 1,653
  • 2
  • 9
  • 25

2 Answers2

3

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) }
})
Barney
  • 16,181
  • 5
  • 62
  • 76
0

All right.. I figured it out. I made a separate function and found the element using DOM and got the value from there:

function boxValue() {
  alert(document.getElementById('searchBox').value);
}
m('input', {
    id: 'searchBox',
    placeholder: 'Type to search...',
    oninput: () => { boxValue() }
})

I'll be marking this as the solution for now (as soon as I can), but if anyone comes up with a better answer, I will change the accepted answer.

Sujit
  • 1,653
  • 2
  • 9
  • 25