Insert into HTML select tag options from a JSON

∥☆過路亽.° 提交于 2019-12-03 08:41:20

You don't need the transform for this, try it this way:

var jsonData = $.parseJSON(window.localStorage.getItem("data"));

var $select = $('#mySelectID');
$(jsonData).each(function (index, o) {    
    var $option = $("<option/>").attr("value", o.CODE).text(o.NAMEVAR);
    $select.append($option);
});

Here is a working fiddle.

$.ajax({
    url:'test.html',
    type:'POST',
    data: 'q=' + str,
    dataType: 'json',
    success: function( json ) {
        $.each(json, function(i, value) {
           $('#myselect').append($('<option>').text(value).attr('value', value));
        });
    }
});

As you are starting you can learn more of JavaScript from w3schools. There is an DOM object called Element that you can use to add an option into select. You just need to do something like:

var el = document.getElementById('mySelectID'); //Get the select element
var opt = document.createElement('option'); //Create option element
opt.innerHTML = "it works!"; //Add a value to the option

el.appendChild(opt); //Add the option to the select element

I think there are a couple of errors in your code. Try this instead:

// it's class, not id, and no fullstop required.
// The $ sign was in the wrong place.
var transform = {tag:'option', class:'$(CODE)', html:'${NAMEVAR}'};

// it's innerHTML not innerHtml
document.getElementById('mySelectID').innerHTML = json2html.transform(jsonData, transform);

to answer the actual question on how to do this in json2html .. with the correct transform

var jsonData = $.parseJSON(window.localStorage.getItem("data"));
var transform = {tag:'option', id:'${CODE}',html:'${NAMEVAR}'};
document.getElementById('mySelectID').innerHtml = json2html.transform(jsonData,transform);

OR using the jquery plugin for json2html

var jsonData = $.parseJSON(window.localStorage.getItem("data"));
var transform = {tag:'option', id:'${CODE}',html:'${NAMEVAR}'};
$('#mySelectID').json2html(jsonData,transform);

most immediately you need to change this:

var jsonData = $.parseJSON(window.localStorage.getItem("data"));
var transform = {tag:'option', id:'.CODE',html:'{$NAMEVAR}'};

To this:

var jsonData = $.parseJSON(window.localStorage.getItem("MyData"));
var transform = {tag:'option', id:'{$CODE}',html:'{$NAMEVAR}'};

That's just a key to get to the data, so make sure you use the same key.

There may be some difficulty in rendering:

value="1"

As you are depending id="{$CODE}" to translate to that, which it will not do automatically.

Good luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!