SteveV SteveV - 3 months ago 7
HTML Question

JSON in Select Box Value

I have the need to store JSON in a HTML Select object, and wondering if it's possible?

For example:

<select id="music" >
<option value={mbid:123,artist:'Judas Priest'};>Heavy Metal 1</option>
<option value="{mbid:456,artist:'Black Sabbath'};">Heavy Metal 2</option>
<option value="{mbid:789,artist:'Iron Maiden'};">Heavy Metal 3</option>
<option value="{mbid:102,artist:'Accept'};">Heavy Metal 4</option>
</select>

$('#music').on('change', function() {
var val = this.value;
alert(val.mbid)
});


JSFiddle example: https://jsfiddle.net/rv7x38cw/

Answer

Can you please modify your HTML and JS code as follows:

https://jsfiddle.net/rv7x38cw/2/

HTML:

<select id="music">
  <option value='{"mbid":123,"artist":"Judas Priest"}'>Heavy Metal 1</option>
  <option value='{"mbid":456,"artist":"Black Sabbath"}'>Heavy Metal 2</option>
  <option value='{"mbid":789,"artist":"Iron Maiden"}'>Heavy Metal 3</option>
  <option value='{"mbid":102,"artist":"Accept"}'>Heavy Metal 4</option>
</select>

JS:

$('#music').on('change', function() {
  var str = this.value;
  alert(str);
  var val = $.parseJSON(str);
  alert(val);
  alert(val.mbid)
});

Here, the key changes are; you have to put value=' your JSON string ' in single quote and each JSON's key name has to be surrounded by double quote like "mbid"

Comments