William
William

Reputation: 4588

Aurelia - how to capture data from multiple form fields and store in model

I am learning Aurelia.

My question:

I have a hard-coded view that looks like this:

app.html

<template> 
    <div>
        <label for="firstname">First Name</label>
        <input type="text" name="firstname" value="Bob">
        <label for="firstname">Last Name</label>
        <input type="text" name="lastname" value="Tanner">
   </div>

   <div>
       <label for="firstname">First Name</label>
       <input type="text" name="firstname" value="Lynda">
       <label for="firstname">Last Name</label>
       <input type="text" name="lastname" value="Kay">
   </div>

    <div>
        <label for="firstname">First Name</label>
        <input type="text" name="firstname" value="Alan">
        <label for="firstname">Last Name</label>
        <input type="text" name="lastname" value="Jones">
   </div>

   <button click.trigger="addEntries()">add entries</button>
</template>

When the user clicks the button I want the result to be a data structure that looks like this:

this.entries = [
  {firstname:"Bob", lastname:"Tanner"},
  {firstname:"Lynda", lastname:"Kay"},
  {firstname:"Alan", lastname:"Jones"}
]

Here is the rest of my code

app.js

import {WorkEntry} from 'components/work_entry';

export class App {
  constructor() {
    this.firstname = "";
    this.lastname = "";
    this.entries = [];
  }

  addEntry(){
    this.entries.push(new WorkEntry(this.firstname,this.lastname))

  }

  addEntries(){
     // ??
     // loop through dom elements ?
  }
}

work_entry.js

export class WorkEntry {
    constructor(firstname,lastname){
        this.firstname = firstname;
        this.lastname = lastname;
    }
}

Upvotes: 0

Views: 476

Answers (1)

mgiesa
mgiesa

Reputation: 1013

You want to loop through your entries array and bind the inputs to the properties of each item.

<template> 
    <div repeat.for="entry of entries">
        <label for="firstname">First Name</label>
        <input type="text" name="firstname" value.bind="entry.firstname">
        <label for="firstname">Last Name</label>
        <input type="text" name="lastname" value.bind="entry.lastname">
    </div>
</template>

If you want the view to begin with data already, just instantiate your this.entries array with that data and it will be displayed. If the user changes the value in the inputs, the corresponding item in the array will also be updated with that value.

Upvotes: 1

Related Questions