开发者

Pushing select element value as json

开发者 https://www.devze.com 2023-03-17 20:54 出处:网络
Due to the limitations of the deign of a current system, I need to pass data to a select element as json, reset each option in the select object with the \'id\' value from the json and populate a seco

Due to the limitations of the deign of a current system, I need to pass data to a select element as json, reset each option in the select object with the 'id' value from the json and populate a second select element with 'sid' data from the json to create a dynamic parent-child pair of se开发者_JS百科lect elements.

However I seem to be unable to successfully parse the option value and push it into an array for use in later code.

<select id="Sector">
    <option value="{'id':'Fruit','sid':['Apple','Orange']}"></option>
    <option value="{'id':'Veg','sid':['Tomato','Carrot']}"></option>
</select>

<script language="JavaScript" type="text/javascript">

    var plist = document.getElementById('Sector');
    var opts = plist.options;
    var x =[];
    for(i=0;i<opts.length;i++){
        x.push(opts[i].value);
    }

    alert(x[0]['id']);
</script>

What am I doing wrong ??i


The option values are strings. If you want to treat them as JavaScript objects, you have to run them through a JSON parser.

You will then run into another problem as the option values are not JSON. Use JSON Lint to find your errors (I can't see any aside from you using a ' every place you should be using a "). If you are dealing with JSON, you should almost always be building a data structure in a programming language and then running it through a JSON serializer, handcrafting JSON is asking for trouble.


this line is an issue

   x.push(opts[0]);

first off, I think you need to do opts[0].value, then I think you need to use eval or JSON.parse to turn it into an object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号