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/
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"
You can also checkout in below live fiddle.
$('#music').on('change', function () {
var str = this.value;
alert(str);
var val = $.parseJSON(str);
alert(val);
alert(val.mbid)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<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>
As described in HTMLOptionElement: value DOMString Reflects the value of the value HTML attribute, if it exists; otherwise reflects value of the Node.textContent property.
And:
DOMString is a UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String.
So, yes, you can use a json value, but this value must be serialized as string:
$(function () {
$('#music').on('change', function() {
var val = JSON.parse(this.value);
console.log(val.mbid);
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With