Home » Jquery » javascript – How to store & retrieve an object as a value in option of select element?

javascript – How to store & retrieve an object as a value in option of select element?

Posted by: admin February 22, 2020 Leave a comment

Questions:

How to store & retrieve an object as a value for option of select element?

<select>
  <option value = "{}" selected>lorem</option>
</select>
How to&Answer:

This isn’t a great pattern to use. You should have the select use some UUID (or a unique ID field from you object) as the value for your select, and use the name or description to display to the user.

Then on form submission, you can use Array.find() to get the object that was selected.

Answer:

agree with KiaiFighter. create an array of objects. and populate/create your options from it. then use the filter function to retrieve the selected object. run the snippet below for an example

const myarray = [
  {value: 'one', text: 'one', otherstuff: 'A'},
  {value: 'two', text: 'two', otherstuff: 'B'},
  {value: 'three', text: 'three', otherstuff: 'C'},
  {value: 'four', text: 'four', otherstuff: 'D'},
]

const options = myarray.map(x => `<option value="${x.value}">${x.text}</option>`);
$('#myselect').append(options);

// find elements
$('#mybutton').click(()=> console.log(myarray.filter(x => x.value == $('#myselect').val())[0]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id = "myselect">
 </select>

<button id="mybutton">
submit
</button>