SteveV SteveV - 2 years ago 139
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>

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

JSFiddle example:

Answer Source

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


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


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

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"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download