DEV Community

artydev
artydev

Posted on

Dynamic Properties

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.

<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

Top comments (0)