DEV Community

artydev
artydev

Posted on

1 1

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more