-1

I have a simple form with a drop-down list, I would like to pre-fill two other input forms based on the pick in the drop-down list.

My code:

<select>
  <option person="ben">Ben</option>
  <option person="henry">Henry</option>
  <option person="julia">Julia</option>
  <option person="joe">Joe</option>
</select>

<br/>
<br/>
<b>Age</b>
<br/>
<input type="text" age="age">
<br/>
<b>Gender</b>
<br/>
<input type="text" gender="gender">

Lets assume that I pick Julia in the drop-down list, then I would like age and gender to be filled automatically, but can be changed by the user at any time after the automatic fill. I am new to all this, but I'll guess JavaScript is the way to go (jQuery or so).

I would really appreciate if you could show me an example on this.

It'sOK
  • 65
  • 1
  • 8

2 Answers2

1

You can use JQuery:

const peopleData = {
  'Ben'  : { age: 42, gender: 'Male' },
  'Henry': { age: 21, gender: 'Male' },  
  'Julia': { age: 35, gender: 'Female' },
  'Joe'  : { age: 19, gender: 'Male' }
}

$(document).ready(function(){
  $("#person").change(function() {
    var person = $(this).val();
    $('#age').val(peopleData[person].age)
    $('#gender').val(peopleData[person].gender)
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="person">
  <option person="ben">Ben</option>
  <option person="henry">Henry</option>
  <option person="julia">Julia</option>
  <option person="joe">Joe</option>
</select>
<hr/>
<div>Age</div>
<input type="text" id="age">
<div>Gender</div>
<input type="text" id="gender">

This uses a JSON object with data about each person.

When a person is selected in the menu, it sets the values of the input fields based on the person's corresponding data.

Demo

Dan Kreiger
  • 5,358
  • 2
  • 23
  • 27
0

const ageInput = document.querySelector("[age]")
const genderInput = document.querySelector("[gender]")

document.querySelector("select").addEventListener("change", (e) => {
  if (e.target.value === "Julia") {
    ageInput.value = 21
    genderInput.value = "female"
  }
})
<select>
  <option person="ben">Ben</option>
  <option person="henry">Henry</option>
  <option person="julia">Julia</option>
  <option person="joe">Joe</option>
</select>

<br/>
<br/>
<b>Age</b>
<br/>
<input type="text" age="age">
<br/>
<b>Gender</b>
<br/>
<input type="text" gender="gender">
marzelin
  • 10,790
  • 2
  • 30
  • 49