Dynamic Properties
Tags: javascript, properties
Published: 2020-04-27 11:58:44

This feature is often underused among Javascript users. I can't recall where I read the first article mentioning it. Nonetheless here is a simple use case.

```html
<form action="javascript:submit()">
 <label>FirstName</label> <input class="dp" type="text" name="firstName"/>
  <label>LastName</label><input class="dp" type="text" name="lastName" />
  <label>Age</label><input class="dp" type="text" name="age" />
  <label>Fruits</label><select class="dp" name="fruits">
    <option>apple</option>
    <option>bananas</option>
    <option>orange</option>
  </select>
  <input type="submit" value="submit">
  <p id="output"></p>
</form>

<script>
let user = {
  firstName: '',
  lastName: '',
  age: '',
 
};
    
let template = (user) => `
<pre>
  {
    firstName : ${user.firstName}
    lastName  : ${user.lastName}
    age  : ${user.age}
  }
</pre>
<hr />
<pre>
  ${ JSON.stringify(user)}
</pre>
`

function validate(field, value) {
  let error = (field  === "age") && (parseInt(value) < 18)
  return  error  && `<span style='color:red'>${value}</span>` || value
}

function handle(e) {
  const {name, value} =  event.target;
  user[`${name}`] = validate(name, value);
  //displayPerson();
}

let displayPerson = () => {
  document
    .querySelector('#output')
    .innerHTML =  template(user);
}

function submit () {
  displayPerson()
}

document
  .querySelectorAll(".dp")
  .forEach((el) => {
    el.oninput = handle;
})
</script>
```

You can test it here : [Dynamic Properties](https://flems.io/#0=N4IgzgpgNhDGAuEAmIBcIB0ALeBbKIANCAGYCWMYaA2qAHYCGuEamO+RIsA9nYn6wA8UMnQDWAAiwAnCCQC8AHRA54ABzCoA9FpK94YDAHNu3IzAZqyhnri2wwYAEwB+EkwoBPeQHVu0sQBqAGUGOk0AdyMcAAEAFgAGBIAyJGs1KAZvMAjLZQlZKCVweE9KLAgIeGUAPkU6esEsJzq6CQkAEU9GXDJYCQAFaW41CGl4MggwRq1m1sE1CVhMx2LReGHa+vaAFSxrCRIIBngAV1kJA+4SfglTuiQx08gkCSZeIwkAKQYANwYwLBpGQ1PA7pBpIYJABJJZhADkYNksAYUCgEgiFQusNkDFe8AqhzIkLBDHGfRgEmYfDIvDook+ZHgGAkAD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