skip to Main Content

Good day, seniors!

Ignore the choice of ids, names, names of variables. I was just testing this code first before putting it in the project I’m working on. Thank you in advance!

I can’t seem to get the selected value of the select element and add it in an array of object

here’s the code:

let list = [];
let selectedVal;

function changes(event) {
  selectedVal = event.target.value;
  list.push({
    selectedVal
  })
}

const selectEls = document.querySelectorAll("select");

selectEls.forEach((select) => {
  select.addEventListener('change', changes);
});


const addDets = (ev) => {
  ev.preventDefault();
  let officials = {
    name: document.getElementById("name").value,
    age: document.getElementById("age").value,
    favColor: selectedVal,
    location: selectedVal
  }
  list.push(officials)
  document.forms[0].reset();
  console.log(list);
}

document.addEventListener("DOMContentLoaded", () => {
  document.getElementById('btn').addEventListener('click', addDets);
});
<body>
  <form action="" id="form">

    <label for="name">Name:</label>
    <input type="text" name="name" id="name">

    <label for="age">Age:</label>
    <input type="number" name="age" id="age">

    <select name="favorites" id="fav">
      <option value="" selected disabled>Favorite Colors</option>
      <option value="Red">R</option>
      <option value="Blue">B</option>
      <option value="Yellow">Y</option>
    </select>

    <select name="location" id="loc">
      <option value="" selected disabled>Location</option>
      <option value="L">L</option>
      <option value="V">V</option>
      <option value="M">M</option>
    </select>

    <button id="btn" type="submit">OK</button>

  </form>
</body>

</html>

2

Answers


  1. What’s going wrong:

    You are using selectedVal to retrieve the values of select elements. The issue here is that you are trying to store multiple values into a single variable. Thus, when you select red for example, selectedValue will contain red and update both favColor and location with that value.

    Instead, you can simply retrieve their value the same way you retrieved the value of name and age.

    document.getElementById("fav").value;
    document.getElementById("loc").value
    

    keep in mind that this will return the value rather than the option, so if you pick the color R it will store the value Red.

    Working snippet:

    let list = [];
    
    const addDets = (ev) => {
      ev.preventDefault();
      let officials = {
        name: document.getElementById("name").value,
        age: document.getElementById("age").value,
        favColor: document.getElementById("fav").value,
        location: document.getElementById("loc").value
      }
      list.push(officials)
      document.forms[0].reset();
      console.log(list);
    }
    
    document.addEventListener("DOMContentLoaded", () => {
      document.getElementById('btn').addEventListener('click', addDets);
    });
    <body>
      <form action="" id="form">
    
        <label for="name">Name:</label>
        <input type="text" name="name" id="name">
    
        <label for="age">Age:</label>
        <input type="number" name="age" id="age">
    
        <select name="favorites" id="fav">
          <option value="" selected disabled>Favorite Colors</option>
          <option value="Red">R</option>
          <option value="Blue">B</option>
          <option value="Yellow">Y</option>
        </select>
    
        <select name="location" id="loc">
          <option value="" selected disabled>Location</option>
          <option value="L">L</option>
          <option value="V">V</option>
          <option value="M">M</option>
        </select>
    
        <button id="btn" type="submit">OK</button>
    
      </form>
    </body>
    
    </html>
    Login or Signup to reply.
  2. Skip all the ids of the input elements and just use the name attribute. On the submit event the form is ev.target and then you can get all the values by ev.target.[name].value.

    let list = [];
    
    const addDets = (ev) => {
      ev.preventDefault();
      let officials = {
        name: ev.target.name.value,
        age: ev.target.age.value,
        favColor: ev.target.favorites.value,
        location: ev.target.location.value
      }
      list.push(officials);
      ev.target.reset();
      console.log(list);
    }
    
    document.addEventListener("DOMContentLoaded", () => {
      document.forms.form.addEventListener('submit', addDets);
    });
    <form action="" name="form">
    
      <label>Name: <input type="text" name="name"></label>
    
      <label>Age: <input type="number" name="age"></label>
    
      <select name="favorites">
        <option value="" selected disabled>Favorite Colors</option>
        <option value="Red">R</option>
        <option value="Blue">B</option>
        <option value="Yellow">Y</option>
      </select>
    
      <select name="location">
        <option value="" selected disabled>Location</option>
        <option value="L">L</option>
        <option value="V">V</option>
        <option value="M">M</option>
      </select>
      
      <button>OK</button>
    </form>

    An alternative could be to use FormData() for getting all values and then run through the entities.

    let list = [];
    
    const addDets = (ev) => {
      ev.preventDefault();
      let formData = new FormData(ev.target);
      let officials = {};
      [...formData.entries()].forEach(ent => officials[ent[0]] = ent[1]);
      list.push(officials);
      ev.target.reset();
      console.log(list);
    }
    
    document.addEventListener("DOMContentLoaded", () => {
      document.forms.form.addEventListener('submit', addDets);
    });
    <form action="" name="form">
    
      <label>Name: <input type="text" name="name"></label>
    
      <label>Age: <input type="number" name="age"></label>
    
      <select name="favorites">
        <option value="" selected disabled>Favorite Colors</option>
        <option value="Red">R</option>
        <option value="Blue">B</option>
        <option value="Yellow">Y</option>
      </select>
    
      <select name="location">
        <option value="" selected disabled>Location</option>
        <option value="L">L</option>
        <option value="V">V</option>
        <option value="M">M</option>
      </select>
      
      <button>OK</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search