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.
>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>