In this chapter, you will learn how to use forms in Aurelia framework.
First, we will see how to submit an input form. The view will have two input forms for username and password. We will use value.bind for data binding.
<template> <form role = "form" submit.delegate = "signup()"> <label for = "email">Email</label> <input type = "text" value.bind = "email" placeholder = "Email"> <label for = "password">Password</label> <input type = "password" value.bind = "password" placeholder = "Password"> <button type = "submit">Signup</button> </form> </template>
The signup function will just take the username and password values from the inputs and log it in the developer’s console.
export class App { email = ''; password = ''; signup() { var myUser = { email: this.email, password: this.password } console.log(myUser); }; }
The following example will demonstrate how to submit a checkbox with Aurelia framework. We will create one checkbox and bind the checked value to our view-model.
<template> <form role = "form" submit.delegate = "submit()"> <label for = "checkbox">Checkbox</label> <input type = "checkbox" id = "checkbox" checked.bind = "isChecked"><br/> <button type = "submit">SUBMIT</button> </form> </template>
Form submitting will just log the checked value in the console.
export class App { constructor() { this.isChecked = false; } submit() { console.log("isChecked: " + this.isChecked); } }
The following example will demonstrate how to submit radio buttons. The syntax repeat.for = "option of options" will repeat through an array of objects and create a radio button for each object. This is a neat way of dynamically creating elements in Aurelia framework. Rest is the same as in the previous examples. We are binding the model and the checked values.
<template> <form role = "form" submit.delegate = "submit()"> <label repeat.for = "option of options"> <input type = "radio" name = "myOptions" model.bind = "option" checked.bind = "$parent.selectedOption"/> ${option.text} </label> <br/> <button type = "submit">SUBMIT</button> </form> </template>
In our view-model, we will create an array of objects this.options and specify that the first radio button is checked. Again, the SUBMIT button will just log in the console which radio button is checked.
export class PeriodPanel { options = []; selectedOption = {}; constructor() { this.options = [ {id:1, text:'First'}, {id:2, text:'Second'}, {id:3, text:'Third'} ]; this.selectedOption = this.options[0]; } submit() { console.log('checked: ' + this.selectedOption.id); } }
If we check the third radio button and submit our form, the console will show it.