开发者

how to update a list of html items based on a list of json data

开发者 https://www.devze.com 2023-02-19 16:02 出处:网络
I have a list of checkboxes in my html page, like so: <ul id=\"myList\"> <li class=\"checkboxItem\">

I have a list of checkboxes in my html page, like so:

<ul id="myList">
  <li class="checkboxItem">
    <input type="checkbox" name="item1" value="001" id="it开发者_运维问答em-1"/> 
    <label for="item-1" class="checkboxLabel">Display 1</label>
  </li>
  <li class="checkboxItem">
    <input type="checkbox" name="item2" value="042" id="item-2"/>
    <label for="item-2" class="checkboxLabel">Display 42</label>
  </li> 
</ul>

now I make a call to get some json data, which comes back like so:

[{"name":"002","title":"Display 1"}]

what I want to do is loop the returned json and update the list of checkboxes such that any item not in the returned list is disabled, and those where the title matches a given label, the input value is updated.

so in this example, item2 will be disables and item1 will have its value updates to 002.

here's what I have so far, i'm not quite sure where to go from here, that is, what to do inside the loop. I do have some control over how the json is returned, so if it makes sense to retunr the json in another format, I can do that.

EDIT, updated the function, see below. however, once I get inside the for loop inside the each function, elem is getting a value of "0" rather than a js object such as: {"name":"002","title":"Display 1"}. clearly data, is being transferred from the outside scope of the function to the inside scope of the each function, but how do I make that happen?

function(data) {
        $('#myList').children('li').each(function(i,e) {
            for(var elem in data) {
                var elemDescr = elem['title'];
                var elemName = elem['name'];
                if(elemDescr==$(this).find('.checkboxLabel').text()) {
                    $(this).find('input').attr('value',elemName);
                }
            }
        });


It might be easier to have an outer loop for each checkbox, and an inner loop go through each json element, enabling or disabling based on whether the element/checkboxes have a match.

So an inversion of what you have:

function(data) {
    $('#myList').children('li').each(function() {
        // loop through your data elements here
    });
}

Another option (probably less desirable because it may cause multiple disabled/enabled transitions) is to disable all checkboxes, and enable them as you loop through each element.


I have found my problem. rather than doing:

for(var elem in data) {
            var elemDescr = elem['title'];
            var elemName = elem['name'];

        }

I needed to do:

for(var index in data) {
            var elemDescr = data[index].title;
            var elemName = data[index].name;

        }
0

精彩评论

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

关注公众号