Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How select an option with object value in select box?

I have a select box with options, which its options’ value are objects. Like this:

<select id="mySelect" name="mySelect">
    <option value="{name: 'A', age: '20'}">A</option>
    <option value="{name: 'B', age: '30'}">A</option>
    <option value="{name: 'C', age: '40'}">A</option>
</select>

I need to know when I get an object like this, {name: 'B', age: '30'} from api, how can I select the option which has this object as value in HTML?
In this case I want to second option be selected.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can select the desired option using a common css selector for those elements having a specified value attribute (as string).

I show you in this demo a function selectOptionByJSONValue that accepts a jsonValue string and will return the corresponding option. This demo selects the C option when the page is loaded, by finding it using the input variable as json value, and setting its selected attribute.

In all fairness in case of doing it again on the same select element, all options should have the selected attribute removed before any one else gets it after.

const input = "{name: 'C', age: '40'}";
const option = selectOptionByJSONValue(input);
option.setAttribute('selected', true);

function selectOptionByJSONValue(jsonValue){
  const optionSelector = `#mySelect option[value="${jsonValue}"]`;
  return document.querySelector(optionSelector);  
}
<select id="mySelect" name="mySelect">
    <option value="{name: 'A', age: '20'}">A</option>
    <option value="{name: 'B', age: '30'}">B</option>
    <option value="{name: 'C', age: '40'}">C</option>    
</select>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading