-3

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.

Atousa Darabi
  • 847
  • 1
  • 7
  • 26
  • It's not clear to me what you're asking. The value is always a string, are you just looking to parse that string as JSON? Something else? Perhaps you could show your attempt and indicate specifically what isn't working as expected? – David Jun 24 '22 at 11:19
  • @David I get the value {name: 'B', age: '30'} from api, and in HTML I want to the option with this value be selected – Atousa Darabi Jun 24 '22 at 11:21
  • 1
    If you want to find the option that has this specific string value set, then you can use `querySelector` with an attribute selector, and in combination with https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape to make that string valid inside a selector. – CBroe Jun 24 '22 at 11:22
  • 1
    Related: https://stackoverflow.com/questions/13343566/ – amiria703 Jun 24 '22 at 11:26
  • @amiria703 your link has simple value, The values on your links are not objects. – Atousa Darabi Jun 24 '22 at 11:28
  • 1
    @AtousaDarabi Can you change the `value` field to be valid json? You would have this instead `value="{"name": "A", "age": "20"}"`? In the current state it's a bit difficult to parse the data of the `value` field and compare to what your API returned. – Idrizi.A Jun 24 '22 at 11:30
  • 1
    @AtousaDarabi: The value is *always a string*. The strings you're using are (almost) JSON (but need to use double-quotes instead of single-quotes). You can get or set the selected value exactly as you would any other *string* value, it doesn't really matter what characters are contained within that string or what object it may represent when de-serialized. Again, have you tried anything at all? What isn't working in your code? – David Jun 24 '22 at 11:40

3 Answers3

3

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>
Diego D
  • 6,156
  • 2
  • 17
  • 30
1

This should do the job:

const sel=document.getElementById("mySelect"), btn=document.querySelector("button");

[...sel.options].forEach(o=>{
  if (o.value) o.value=JSONstring(o.value)     // standardize the option values using JSONstring()
})

document.body.onclick=ev=>{ 
 if (ev.target.tagName!=="BUTTON") return
 sel.value=JSONstring(ev.target.textContent);  // find the selection option with the correct value and select it
}

function JSONstring(str){  // converts any "object describing string" into a sorted and valid JSON string - if possible ...
 return JSON.stringify(Object.fromEntries(Object.entries(eval("("+str+")")).sort(([k1],[k2])=>k1.localeCompare(k2))))
}
<select id="mySelect" name="mySelect">
    <option value="">Please choose ...</option>
    <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>

<button> {name:       'B'  , age:"30"}</button>
<button>{age:"40", name:   'C'} </button>

Please note that I am using eval() to convert your "object describing string" into a sorted and standardised JSON format. This can then very easily be used to set the select filed accordingly. eval() is shunned by many developers as being "unsafe". However, I believe that the associated risk in this use case is acceptable.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
0

You can get the value you selected by change event. Also, you can set an option by default by "selected" attribute.

const select = document.getElementById('mySelect');

select.addEventListener('change', function (event) {
 console.log(event.target.value)
});
<select id="mySelect" name="mySelect">
    <option value="{name: 'A', age: '20'}">A</option>
    <option value="{name: 'B', age: '30'}" selected>B</option>
    <option value="{name: 'C', age: '40'}">C</option>
</select>
Mina
  • 14,386
  • 3
  • 13
  • 26