The issue is your onchange
attribute currently has a string-based value and it is effectively eval
d when the change event is fired. As @PeterSeliger comments, regForm
simply returns a function.
regForm
could return anything, and so the default change handler makes no assumptions about your answer. You maybe be expecting that the returned function would be called with the event, but instead the default handler simply discards the value.
One solution would be to use JavaScript's onchange
property, instead of HTML's onchange
attribute -
const person = {
name:'',
age:''
}
const regForm = field => event =>
person[field] = event.target.value
const form =
document.forms.sample
form.name.onchange = regForm("name")
form.age.onchange = regForm("age")
form.onsubmit = event => {
event.preventDefault()
console.log("Submitted", JSON.stringify(person))
}
<form id="sample">
<input name="name" placeholder="enter your name" />
<input name="age" placeholder="enter your age" />
<input type="submit" />
</form>
And since you are familiar with event delegation, ie event.target
, you can remove additional duplication. Looks like regForm
just kinda disappeared! -
const data =
{}
const form =
document.forms.sample
form.onchange = event =>
data[event.target.name] = event.target.value
form.onsubmit = event => {
event.preventDefault()
console.log("Submitted", JSON.stringify(data))
}
<form id="sample">
<input name="name" placeholder="enter your name"><br>
<input name="age" placeholder="enter your age"><br>
<input name="foo" placeholder="enter your foo"><br>
<input name="bar" placeholder="enter your bar"><br>
<input type="submit" />
</form>
Output
Submitted {"name":"1","age":"2","foo":"3","bar":"4"}
Functions that take other functions as input and/or return other functions as output are called higher-order functions. There are a variety of terminologies and techniques for dealing with them. For related reading, see What do multiple arrow functions mean?
const preventDefault = f => event =>
( event.preventDefault()
, f(event)
)
const logKeypress = event =>
console.log(event.which)
document
.querySelector('input[name=foo]')
.addEventListener('keydown', preventDefault(logKeypress))
<input name="foo" placeholder="type here to see ascii codes" size="50">